I am new to SQL and I started building my own project. I am having issues creating a foreign key on my second table. . Please let me know what I am missing here.
The second CREATE TABLE statement should be:
CREATE TABLE entry (
issuer_id INT AUTO_INCREMENT PRIMARY KEY,
issuer_name VARCHAR(20) NOT NULL,
fine INT,
book_id INT,
due_date DATE,
FOREIGN KEY (book_id)
REFERENCES book_table (book_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (due_date)
REFERENCES book_table (due_date)
ON DELETE CASCADE
ON UPDATE CASCADE
);
A foreign key is a column or set of columns in one table that links to a unique key (typically the primary key) in another table. The columns must exist in both tables. They must match in type and the order within the key declarations. They must constitute a unique key in the foreign table.
Related
I'm trying to create two relations by MySQL, while I was creating the second relation "t2", I added a foreign constraint to the first relation "t1".
The first table "t1" was been built successfully, but it showed "Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'FK2' in the referenced table 't1'" during creating the second table "t2".
I have checked some issues like mine, some solutions were the referenced attribute in the first table should be unique or primary key. But "Mon" already has been the PK in the first table.
What's wrong in my code?
create table t1
( Num INT(10) NOT NULL,
Mon VARCHAR(7) NOT NULL,
CONSTRAINT PK1 PRIMARY KEY (Num, Mon)
);
CREATE TABLE t2
( Num INT(10) NOT NULL,
Mon VARCHAR(7) NOT NULL,
Totle_Income Decimal(9,2) DEFAULT 0,
CONSTRAINT PK2 PRIMARY KEY (Num, Mon),
CONSTRAINT FK1 FOREIGN KEY (Num) REFERENCES t1(Num)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK2 FOREIGN KEY (Mon) REFERENCES t1(Mon)
ON DELETE CASCADE ON UPDATE CASCADE
);
t1.mon is only the second component of the primary key, thus also only the second component of the index. That doesn't usefully index t1.mon, it needed to be the first or only component of the index.
But you likely want to reference the complete key. So the foreign key constraint should include both columns rather than having two constraints for each part of the key.
...
CONSTRAINT FK1
FOREIGN KEY (Num,
Mon)
REFERENCES t1
(Num,
Mon)
ON DELETE CASCADE
ON UPDATE CASCADE,
...
t1.monis not unique and therefore can not be refered as a foreign_key
I'm working on a project which involves implementing a simplified version of a school database. The 3 relevant tables are listed below:
create table classes( --A given class
class_code varchar(10) primary key
);
create table class_offerings( --A particular instance of a class
class_code varchar(10),
class_name varchar(128) not null,
semester_code integer,
maximum_capacity integer check (maximum_capacity >= 0),
teacher_name varchar(50) not null, --heavily simplified
primary key (class_code, semester_code),
foreign key (class_code) references classes(class_code)
on delete cascade on update cascade
);
create table prerequisites(
prereq varchar(10),
class_code varchar(10),
semester_code integer,
primary key (class_code, semester_code),
foreign key (class_code) references classes(class_code)
on delete cascade on update cascade,
foreign key (semester_code) references class_offerings(semester_code)
on delete cascade on update cascade,
foreign key (prereq) references classes(class_code)
on delete cascade on update cascade
);
When I try and create "prerequisites," I'm given the message "ERROR: there is no unique constraint matching given keys for referenced table class_offerings." While it is true that I haven't applied the UNIQUE constraint to semester_code, it's part of the primary key, which to my understanding enforces a unique combination of all elements in the primary key. If I turn out to be wrong, I still don't want to have to apply UNIQUE to the semester_code, as multiple entries of the same semester_code should be allowed provided they don't share the same class_code. How do I fix this error?
Foreign keys can also be made up of several columns:
foreign key (class_code, semester_code)
references class_offerings(semester_code,class_code)
on delete cascade on update cascade,
Personally however, I would avoid such a design. If possible I would introduce artificial IDs as auto-increment columns that always serve a primary keys. That way foreign keys always can be on the artificial ID column.
Natural keys are good and should be put as constraints to the db as well, I would just not build relationships on natural keys. However, this is my personal preference and there are arguments for having natural keys a primary keys as well: https://sqlstudies.com/2016/08/29/natural-vs-artificial-primary-keys/
I created a table where cat_parent_id is a foreign key is constrained by the primary key cat_id, using this:
CREATE TABLE categories (
cat_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
cat_parent_ID SMALLINT,
cat_name VARCHAR(40)
INDEX cat_id(cat_id),
FOREIGN KEY(cat_id) REFERENCES categories(cat_id),
);
When I try to insert a record where cat_parent_ID is NULL, I get the error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`categories`, CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`cat_id`) REFERENCES `categories` (`cat_id`))
How can the foreign key constraint fail when there is no foreign key to begin with? Is the constraint only possible if null is not allowed?
I can only insert records successfully if I disable the constraint, which is not what I want. I need the parent_id to be optional, and if it has a value then it be an existing cat_id only
This will create a circular foreign key, which will prevent any insertion into the table.
FOREIGN KEY(cat_id) REFERENCES categories(cat_id),
EDIT: Perhaps you meant to put the PK on cat_parent_id?
You have one root record which doesn't have a parent. For this one, you must first disable foreign key constraints.
SET FOREIGN_KEY_CHECKS=0;
Insert the record.
Then don't forget to re-enble foreign key constraints
SET FOREIGN_KEY_CHECKS=1;
Then from now own, make sure your inserts include an existing parent.
How can the foreign key constraint fail when there is no foreign key
to begin with? Is the constraint only possible if null is not allowed?
If you want to add other records which do not have a FK value, make sure that NULL is allowed.
I only get an error 150 when I run this. The other tables are InnoDB, the types are primary key, and the data types match. So I can't see what I'm doing wrong, (and I see no obvious syntax errors). Any ideas?
CREATE TABLE grouptosite (
groups_id BIGINT(20),
usertogroup_groupID BIGINT(20),
usertogroup_userID BIGINT(20),
usertosite_id INT(10),
gts_id INT(10) AUTO_INCREMENT NOT NULL,
PRIMARY KEY (gts_id),
index (gts_id),
index (groups_id),
index (usertogroup_groupID),
index (usertogroup_userID),
index (usertosite_id),
FOREIGN KEY (groups_id)
REFERENCES groups(id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (usertogroup_groupID, usertogroup_userID)
REFERENCES usertogroup(groupID, userID)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (usertosite_id)
REFERENCES usertosite(id)
ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=INNODB;
Are you sure your columns are the same type? I first created the usertosite table with the id of BIGINT (following the same pattern of the other tables), but the grouptosite.usertosite_id column was INT: http://sqlfiddle.com/#!2/d821a.
As mentioned in another comment, datatypes for foreign keys need to be the same.
I have the following SQL statements:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);
CREATE TABLE fake(
Name varchar(255),
PName varchar(255),
PGeburtsdatum date,
CONSTRAINT pk_fake PRIMARY KEY (Name,PName,PGeburtsdatum),
CONSTRAINT fk_PName2 FOREIGN KEY (PName) REFERENCES patient(Name) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_PGeburtsdatum FOREIGN KEY (PGeburtsdatum) REFERENCES patient(Geburtsdatum) ON DELETE CASCADE ON UPDATE CASCADE
);
This gives me the error "#1215 - Cannot add foreign key constraint". If I remove the last constraint in the second table creation everything works. All my other foreign key constraints work exactly the same way. What am I missing here?
Not sure why you tagged a mysql question as db2. Anyway, the MySQL documentation states:
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan
So add an index in the Geburtsdatum column:
CREATE TABLE patient(
Name varchar(255),
Geburtsdatum date,
INDEX (Geburtsdatum),
CONSTRAINT pk_patient PRIMARY KEY (Name,Geburtsdatum)
);