I want to create two tables. practice has a AUTO_INCREMENT attachment and is a PRIMARY KEY. continued has the id entity continued_id which exists as a FOREIGN KEY that references practice(user_id). Mysql executes the code below fine until line 19, where I receive the 1364 error, stating that continued_id has no default value.
I am confused. I thought that user_id, which auto_increments, and it being the PK, would have a defining value of 1,2,3... I thought that continued_id is equivalent to user_id, and therefore its default value is 1? Perhaps I am misunderstanding how PK's and FK's actually work in sql?
Error:
20:03:02 INSERT INTO continued(hobby) VALUES("Tennis") Error Code: 1364. Field 'continued_id' doesn't have a default value 0.000 sec
CREATE TABLE practice(
user_id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
user_name VARCHAR(60) NOT NULL,
user_real_name VARCHAR(60) NOT NULL
);
CREATE TABLE continued(
continued_id INT NOT NULL,
FOREIGN KEY(continued_id)REFERENCES practice(user_id),
hobby VARCHAR(25) NOT NULL
);
INSERT INTO practice(user_name,user_real_name)
VALUES("KittenKing","Henry");
INSERT INTO practice(user_name,user_real_name)
VALUES("DogDictator","Mary");
INSERT INTO practice(user_name,user_real_name)
VALUES("HamsterHam","Denver");
INSERT INTO continued(hobby)
VALUES("Tennis");
INSERT INTO continued(hobby)
VALUES("Hockey");
INSERT INTO continued(hobby)
VALUES("Spear Hunting");
SELECT * FROM practice,continued;
Your inserts into
continuedneed to be linked to an entry inpractice. You can either do that by immediately following the insert intopracticewith an insert intocontinuedusingLAST_INSERT_ID()forcontinued_id:or by referring to the appropriate entry in
practiceusing anINSERT ... SELECTquery:or
Demo on dbfiddle
Note that you do not need to declare
continued_idasAUTO_INCREMENT.