I'm trying to insert this code into my Albums table on my MySQL database
INSERT INTO `Albums` (`Albumid`, `Name`, `Numberoftracks`, `Artistid`, ]
`Genre`) VALUES (1, "Innuendo", 12, "Queen", "Rock");
But every time I try to I keep getting this error.
1452 - Cannot add or update a child row: a foreign key constraint fails
(`b4014107_db1/Albums`, CONSTRAINT `Albums_ibfk_1` FOREIGN KEY (`Artistid`)
REFERENCES `Artist` (`Artistid`))
I know it's something to do with my foreign key within the table, but I need to manually enter the foreign key because it's not auto-incremented.
Here's the tables code.
CREATE TABLE `Albums` ( `Albumid` int(6) NOT NULL, `Name` varchar(50) NOT
NULL, `Numberoftracks` int(11) NOT NULL, `Artistid` int(6) NOT NULL,
`Genre` varchar(50) NOT NULL, PRIMARY KEY (`Albumid`), KEY `Artistid`
(`Artistid`), CONSTRAINT `Albums_ibfk_1` FOREIGN KEY (`Artistid`)
REFERENCES `Artist` (`Artistid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1
How do I fix this? I need to input data into the table.
artistid is a foreign key in the table Albums. Parent child relationship error comes when you try to insert a foreign key in child table which is not present in the parent table. artistid is not present in your Artist table.
Also, to add the the datatype of artistid is also different.
Taken from mysql docs
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table.
It will reject any INSERT or UPDATE operation that attempts to create
a foreign key value in a child table if there is no a matching
candidate key value in the parent table.
To remove your error, insert the Queens artist in your Artist table first and then you can insert it into Albums table. Also correct the datatype of column artistid.
Using foreign keys doesn't mean any implicit auto-incrementation. A foreign key in a table means that a record must already exist in another.
see http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html (change version in the url regarding your needs)
Otherwise, make a trigger if you want the artist to be dynamically created.
Hope it'll clarify.
Related
Check out the image below. In the movie_custom table you'll see that when I added a 1:m relationship between plist_field and movie_custom, MySQL Workbench added keys for the attached tables of plist_type and plist_view_type in additional to the key I was expecting.
Why is that?
Can/should I remove them?
Or if I should keep them, how do I auto-insert the key values from the deeper tables when doing an insert into movie_custom and I know a key of plist_field?
If we execute this schema creation:
create table parent
( pid int auto_increment primary key,
theirName varchar(100) not null
);
drop table if exists child;
create table child
( cid int auto_increment primary key,
theirName varchar(100) not null,
pid int not null,
foreign key `fk_c2p` (pid) references parent(pid)
);
Examine what happened to the child:
mysql> show create table child \G;
CREATE TABLE `child` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`theirName` varchar(100) NOT NULL,
`pid` int(11) NOT NULL,
PRIMARY KEY (`cid`),
KEY `fk_c2p` (`pid`), -- ******************** AUTO created by mysql
CONSTRAINT `child_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `parent` (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
From the manual page Using FOREIGN KEY Constraints:
... index_name represents a foreign key ID. The index_name value is
ignored if there is already an explicitly defined index on the child
table that can support the foreign key. Otherwise, MySQL implicitly
creates a foreign key index that is named according to the following
rules:
If defined, the CONSTRAINT symbol value is used. Otherwise, the
FOREIGN KEY index_name value is used.
If neither a CONSTRAINT symbol or FOREIGN KEY index_name is defined,
the foreign key index name is generated using the name of the
referencing foreign key column.
So, back to your questions.
A. Why are they created? They are created because mysql creates them as specified above. They facilitate speedy reversal lookups. When a parent row is to be deleted, a fast non-table scan of children is mandated to allow or disallow the parent row removal. The auto-generated key (or one already satisfying it) is used for this purpose.
B. Should you delete them? No. Why not? Read A.
C. How do you "auto-insert the key values from the deeper tables": you acquire the id of the parent (anywhere in the hierarchy) ahead of time such as using LAST_INSERT_ID() or other program logic.
I am very new to MySQL, just started on it a few days ago. For my homework, the MySQL has its default set to MyISAM for simplicity's sake, and had me created a hospital example database for practice on MySQL.
But for my own personal purpose and some research that InnoDB actually enforces the FK compared to MyISAM, I switched the default to InnoDB and tried to recreate the same database I did for my homework with MyISAM.
And then the problem whacked me like a truck, my "ward" table is the following:
create table Ward
(Code varchar(1) primary key not null,
Name varchar(15) not null,
Consultant varchar(3) not null);
alter table ward
add foreign key (Consultant)
references Doctor(ID);
and my doctor table goes like this:
create table Doctor
(ID varchar(3) primary key not null,
Name varchar(15) not null,
Ward varchar(1) not null);
alter table doctor
add foreign key (Ward)
references Ward(Code);
After that, I tried entering data in either of the tables, and the following errors were given to me when I try to enter data into "ward" table and "doctor" table respectively:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (hospital.ward, CONSTRAINT ward_ibfk_1 FOREIGN
KEY (Consultant) REFERENCES doctor (ID))
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (hospital.doctor, CONSTRAINT doctor_ibfk_1
FOREIGN KEY (Ward) REFERENCES ward (Code))
How do I enter data into either of the tables?
Thanks and sorry for the trouble!
It is probably 'wrong' to have FKs going back and forth like that.
You can disable foreign keys while you create the tables. But then you may have trouble with inserts -- one insert will find a FK violation since you have not done the other yet.
If you don't have loops in your FKs, then simply create the tables in the 'right' order.
I am trying to insert pseudo data into my db to get going, and in one particular table I have two columns which are FK's and PK's of the table; fk_product_manf_code and fk_content_id. To my understanding, these are considered composite keys in their current state.
So I add data to the table:
fk_product_manf_code fk_content_id
NOV-ABC123 1
I then want to associate another content_id to the same product_manf_code, so I perform the following:
INSERT INTO `mydb`.`package_contents`
(`fk_product_manf_code`, `fk_content_id`)
VALUES
('NOV-ABC123', 2);
However I'm greeted with the following error:
Error Code: 1062. Duplicate entry 'NOV-ABC123' for key 'fk_product_manf_code_UNIQUE'
I don't understand what's going, because I thought a composite key makes 2 columns unique? So why is it kicking up a fuss about just 1 column being unique?
Here is the table CREATE statement
CREATE TABLE `package_contents` (
`fk_product_manf_code` varchar(255) NOT NULL,
`fk_content_id` int(11) NOT NULL,
PRIMARY KEY (`fk_content_id`,`fk_product_manf_code`),
UNIQUE KEY `fk_content_id_UNIQUE` (`fk_content_id`),
UNIQUE KEY `fk_product_manf_code_UNIQUE` (`fk_product_manf_code`),
CONSTRAINT `content_id` FOREIGN KEY (`fk_content_id`) REFERENCES `contents` (`content_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `product_manf_code` FOREIGN KEY (`fk_product_manf_code`) REFERENCES `products` (`product_manf_code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
So, you are learning why composite primary keys are a pain, especially for foreign key constraints. Not only are integer keys more efficient, but a single key is easier to work with.
I would suggest changing your table structure to be more like this:
CREATE TABLE package_contents (
package_contents_id int not null auto_increment primary key,
fk_product_manf_id int NOT NULL,
fk_content_id int(11) NOT NULL,
UNIQUE KEY (fk_content_id, fk_product_manf_id),
CONSTRAINT content_id FOREIGN KEY (fk_content_id)
REFERENCES contents(content_id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT product_manf_code FOREIGN KEY (fk_product_manf_id)
REFERENCES products(product_manf_id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Note that I changed the manufacturer code to an id as well. This should also reduce the size of the table, assuming that the "code" is longer than 4 bytes.
If you do this for all your tables, the database will be a bit more efficient, and you won't need superfluous unique constraints. The foreign key constraints should always be to primary keys (unless there is a very good reason for using a different unique key).
I have a table created in MySQL (see the code below). As you see in the code I have a foreign key manager which references the idNo. However I only want to reference to employees with the cat='B'. So I need something like
FOREIGN KEY (manager ) REFERENCES Employee(idNo WHERE cat='B').
Any ideas how I can accomplish this.
idNo SMALLINT AUTO_INCREMENT UNIQUE,
name VARCHAR(25) NOT NULL,
telNo INT(11) NOT NULL,
cat CHAR(1) NOT NULL,
manager SMALLINT,
PRIMARY KEY (idNo ),
FOREIGN KEY (manager ) REFERENCES Employee(idNo) on DELETE CASCADE)ENGINE=INNODB
AUTO_INCREMENT=1000;
Foreign keys do not allow conditions.
If you want to force the condition, you must do it via coding.
It can be done inside your non DB code (Java, PHP, VB,...), or you could create a procedure in MySQL that would be called to perform the insert and that will return an error code if condition is not matched.
If you insert from various codes/application, the procedure is the way to go since it would be centralized.
Create a new UNIQUE KEY in Employee combining idNo and cat.
ALTER TABLE Employee ADD UNIQUE KEY (idNo,cat);
Make a foreign key in the child table that references that new unique key.
ALTER TABLE SomeTable ADD FOREIGN KEY (idNo,cat) REFERENCES Employee(idNo,cat);
Then you just need to make sure cat is constrained to the single value 'B' in the child table. One solution is to create a lookup table containing just the single value 'B'.
CREATE TABLE JustB (cat char(1) PRIMARY KEY);
ALTER TABLE SomeTable ADD FOREIGN KEY(cat) REFERENCES JustB(cat);
Now the only value you can use in the child table is 'B', so naturally it can only reference rows in Employee that have a cat of 'B'.
Another solution would be to use a trigger, but I favor the lookup table.
I am getting an error which I don't understand at all. I am trying to create a table and here is the code:
create table matricula.curso_estudiantes
(codigo varchar(8) NOT NULL,
studentid varchar(8) NOT NULL,
grade varchar(1) NOT NULL,
term numeric(5) NOT NULL,
PRIMARY KEY (codigo, studentid, term),
FOREIGN KEY (codigo)
REFERENCES curso(codigo),
FOREIGN KEY (studentid)
REFERENCES estudiantes(studentid));
insert into matricula.curso_estudiantes values
("COMP2120","X00101010","C",201010),
("COMP2315","X00101010","B",201030),
("COMP2120","X00121111","B",201030),
("COMP2315","X00121111","A",201030),
("COMP2120","X00121234","A",201130),
("COMP2900","X00101010","C",201110),
("COMP3850","X00101010","B",201110),
("COMP2900","X00121111","B",201130),
("COMP3850","X00121111","A",201130),
("COMP2315","X00121234","A",201130),
("COMP2400","X00101010","C",201210),
("MATH1500","X00101010","B",201210),
("COMP2400","X00121111","B",201230),
("MATH1500","X00121111","A",201230),
("COMP3850","X00121234","A",201230),
("MATH1500","X00121234","W",201230);
But I get this error instead:
Error Code:
constraint fails (`matricula`.`curso_estudiantes`, CONSTRAINT
`curso_estudiantes_ibfk_2` FOREIGN KEY (`studentid`) REFERENCES
`estudiantes` (`studentid`))
What seems to be the problem? It creates the table, BUT it gives me that problem and no records are inserted into the table. Which query resolves this? I am new to mySQL so I use a lot of references and examples form the professor.
Do you have the correct corresponding records in the estudiantes table?
A FOREIGN KEY means you need data in the referenced table, or the INSERT won't work.
To fix it, first create and populate your estudiantes and curso tables with valid data.