I have a table horse and a view view_horse that selects every column from the horse table except the primary key (primary key is auto-increment integer) and then presents it to the user, I want to insert data into that views underlying table and naturally expect the primary key to be automatically generated. But I keep getting an SQL exception stating "field of view view_horse underlying doesn't have a default value" when I try to insert any data into it.
EDIT -
CREATE TABLE IF NOT EXISTS `TRC`.`horse` (
`horse_id` INT NOT NULL AUTO_INCREMENT,
`registered_name` VARCHAR(20) NOT NULL,
`stable_name` VARCHAR(20) NOT NULL,
`horse_birth_year` DATE NOT NULL,
`horse_height` DECIMAL(3,1) NOT NULL,
`horse_location` VARCHAR(50) NOT NULL DEFAULT 'TRC',
`arrival_date` DATE NOT NULL,
`passport_no` MEDIUMTEXT NULL,
`is_deceased` TINYINT(1) NOT NULL,
`arrival_weight` DECIMAL NOT NULL,
`horse_sex` VARCHAR(8) NOT NULL,
`microchip_no` VARCHAR(15) NULL,
`date_of_death` DATE NULL,
PRIMARY KEY (`horse_id`),
INDEX `fk_Horses_SexLookup1_idx` (`horse_sex` ASC),
CONSTRAINT `fk_Horses_SexLookup1`
FOREIGN KEY (`horse_sex`)
REFERENCES `TRC`.`lookup_sex` (`sex`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
USE `TRC`;
CREATE OR REPLACE VIEW `TRC`.`view_horse` AS SELECT
registered_name AS 'Registered Name',
stable_name AS 'Stable Name',
horse_birth_year AS 'Age',
horse_height AS 'Height',
arrival_weight AS 'Weight on Arrival',
horse_sex AS 'Sex',
horse_location AS 'Location',
arrival_date AS 'Date of Arrival',
passport_no AS 'Passport no.',
microchip_no AS 'Microchip no.',
is_deceased AS 'Alive?'
FROM `horse`;
If I insert into the view without specifying the columns it actually completes ok. But not when I give the columns as specified in the view.
You're not trying to INSERT into the actual VIEW are you? Insert into the TABLE, and SELECT from the VIEW.
Edit. Forget it; thanks for the correction Strawberry.
Here's a fiddle that illustrates inserting into the view: http://sqlfiddle.com/#!2/280aa6/1/0
Related
I'm a totally MySQL newcomer. Sr if my question is quite obvious. I got 2 tables
CREATE TABLE tbl_addresses(
PK_ADDRESS_ID int NOT NULL AUTO_INCREMENT,
house_number int NOT NULL,
street varchar(35),
district varchar(35),
city varchar(35),
postcode varchar(8),
PRIMARY KEY (PK_ADDRESS_ID)
);
CREATE TABLE tbl_people(
PK_PERSON_ID int NOT NULL AUTO_INCREMENT,
title varchar(6) NOT NULL, # Master / Mister therefor 6 is max
forename varchar(35) NOT NULL,
surname varchar(35) NOT NULL,
date_of_birth DATE NOT NULL,
contact_number varchar(12) NOT NULL,
FK_ADDRESS_ID int NOT NULL,
PRIMARY KEY (PK_PERSON_ID),
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
);
and I'm trying to import data into these tables from Java using below syntaxes
INSERT INTO tbl_addresses (house_number,street,district,city,postcode) VALUES ('1','abc','','abc','abc');
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number) VALUES ('Mr','Tri ','Nguyen','1991-1-1','0123456789');
I got an error Field 'FK_ADDRESS_ID'doesn't have a default value and data actually goes into tbl_addresses but not tbl_people. Am I missing anything? Thanks in advance!
This error is being caused by that you labelled the FK_ADDRESS_ID field in the tbl_people table as NOT NULL, yet you are trying to do an INSERT without specifying a value for this column.
So something like this would work without error:
INSERT INTO tbl_people (title, forename, surname, date_of_birth,
contact_number, FK_ADDRESS_ID)
VALUES ('Mr', 'Tri', 'Nguyen', '1991-1-1', '0123456789', 1);
You could also specify a default value for FK_ADDRESS_ID (the error message you got alluded to this). Here is how you could adda default value:
ALTER TABLE tbl_people MODIFY COLUMN FK_ADDRESS_ID int NOT NULL DEFAULT 1
But because FK_ADDRESS_ID is a key into another table, the value should really be based on the primary key in tbl_addresses.
The fact that you are using a foreign key isn't the reason that you are getting this error. Let's take a look at your column definition.
FK_ADDRESS_ID int NOT NULL,
This is not null but does not a default. Now a look at your insert statement
INSERT INTO tbl_people (title,forename,surname,date_of_birth,contact_number)
FK_ADDRESS_ID isn't in your column list but it cannot be null and doesn't have a default so what can mysql do? Produce an error of course.
The best bet is to define that column as nullable.
Let's revisit the foreign key constraint.
FOREIGN KEY (FK_ADDRESS_ID) REFERENCES tbl_addresses (PK_ADDRESS_ID)
What this really says is that if you asign a value to FK_ADDRESS_ID that value should be present in PK_ADDRESS_ID column in tbl_address
as a side note, it's customary to use lower case for table/column names.
I keep getting the error code 'ORA-02270' and no matter what I try, I can't seem to fix it. Below are my Create Table statements:
CREATE TABLE student
(
studentID CHAR(8) PRIMARY KEY,
studentName VARCHAR(25) NOT NULL,
studentAddress VARCHAR(30) NOT NULL,
studentDOB DATE NOT NULL,
studentGender CHAR(1) NOT NULL CHECK ((studentGender = 'F') OR (studentGender = 'M')),
studentNationality VARCHAR(15) NOT NULL,
studentCourse VARCHAR(30) NOT NULL,
studentSemesterExcellent CHAR(1) NOT NULL CHECK ((studentSemesterExcellent = 'Y') OR (studentSemesterExcellent = 'N'))
);
CREATE TABLE leaseAgreement
(
leaseNo CHAR(6) PRIMARY KEY,
studentID CHAR(8) NOT NULL,
leaseAccommodationType VARCHAR2(10) NOT NULL,
leaseDuration NUMBER NOT NULL,
leaseStartDate DATE NOT NULL,
leaseEndDate DATE,
studentSemesterExcellent CHAR(1) NOT NULL CHECK ((studentSemesterExcellent = 'Y') OR (studentSemesterExcellent = 'N')),
FOREIGN KEY (studentID) REFERENCES student(studentID),
FOREIGN KEY (studentSemesterExcellent) REFERENCES student(studentSemesterExcellent)
);
Am I not allowed to have two foreign keys from the same table? Please can someone explain this error and point me in the right direction. Thank you.
First, the answer from mustaccio is correct.
The column 'studentSemesterExcellent' in table 'student' is no key column. You can not reference it in a foreign key constraint.
And if you make it unique you can only have two rows in the student table, not what you are intending.
Second, you have tagged the question both with MySQL and Oracle. Choose one!
Third, you only need one FK if it is a not null column. Don't make it harder on yourself.
Fourth, if this is Oracle database, the advice is to only use varchar2() for string data. The char and varchar datatypes exist for compatibility reasons.
I've created a table with 3 columns: postID, userID, and comment.
I have the postID as the primary key, and I am trying to make this auto-increment every time I add a new row to the table.
INSERT INTO CommentTable (postID, userID, comment) VALUES (DEFAULT, "test", "test")
When I run this query, it will run OK once but then when I run it again I get "1062 - Duplicate entry '0' for key 'PRIMARY'".
How do I properly set up an auto-increment primary key?
Here is the table structure:
DROP TABLE IF EXISTS `CommentTable`;
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`commentID`)
)
No need to put the field postID
INSERT INTO CommentTable (userID, comment) VALUES ("test", "test")
Edit your table as:
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL AUTO_INCREMENT,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`postID`)
)
Recently I had the same issue where Auto Increment was not saved. It failed every time I tried to save it. My problem was that I had a record where the value was 0 instead of 1, so I updated that record value to a non-zero value, then tried saving the Auto Increment, and it worked.
The zero(0) value in the Primary Index field was causing the ALTER tablename to fail. Once it worked, I put the value back to 0.
I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.
For the following table:
I'd like to add a constraint that if IsBanned flag is set to true, the BannedOn field cannot be left empty (cannot be set to null).
How can I do this in MySQL? Here's my CREATE syntax:
CREATE TABLE IF NOT EXISTS `fa_ranking_system`.`Player` (
`PlayerID` INT NOT NULL AUTO_INCREMENT,
`FK_ServerID` INT NOT NULL,
`PlayerName` VARCHAR(15) NOT NULL,
`RegDate` DATETIME NOT NULL,
`IsBanned` TINYINT(1) NOT NULL,
`LastUpdatedOn` DATETIME NOT NULL,
`LastUpdatedBy` VARCHAR(20) NOT NULL,
`BannedOn` DATETIME NULL,
PRIMARY KEY (`PlayerID`, `FK_ServerID`),
INDEX `fk_Player_Server_idx` (`FK_ServerID` ASC),
CONSTRAINT `fk_Player_Server`
FOREIGN KEY (`FK_ServerID`)
REFERENCES `fa_ranking_system`.`Server` (`ServerID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Actually, you can not define conditional structures in DDL syntax. Your field can be either NULL or NOT NULL - there's no third option (and it cannot depend of another field in structure)
But you can still emulate desired behavior via triggers. You can interrupt UPDATE/INSERT statement if incoming data is invalid in terms of your logic. That can be done via:
CREATE TRIGGER `bannedOnCheck`
BEFORE INSERT ON `fa_ranking_system`.`Player`
FOR EACH ROW
BEGIN
IF(new.IsBanned && new.BannedOn IS NULL) THEN
SIGNAL 'Integrity check failed: can not set banned without ban date'
END IF
END