I need assistance, my 'Key column' says it does not exist when it clearly does.
CREATE TABLE PUBLISHER (
LISHER_ID INT PRIMARYKEY,
LISHER_NAME VARCHAR(5NNULL,
LISHER_ADDRESS VARCHAR(NOT NULL,
LISHER_PHONE VARCHAR(5) NULL,
LISHER_EMAIL VARCHAR(4) NULL);
The column you name in the FOREIGN KEY clause has to exist in the table on which you're defining the constraint - in this case, it has to be a column in the table CONTRACT.
At a guess, I think you probably want
CREATE TABLE CONTRACT (
...
CONSTRAINT FK_CONTRACT_PUBLICATION FOREIGN KEY (PUBLICATION_PUB_ID)
REFERENCES PUBLICATION (PUB_ID));
You appear to have two mistakes, both from what appears to be copy/paste. In your CONTRACT table, you named the column PUBLICATION_PUB_ID, but in your index definition and your foreign key constraint you tried to reference it as just PUB_ID.
mysql> CREATE TABLE CONTRACT (
-> CON_NUMBER INT NOT NULL PRIMARY KEY,
-> CON_STARTDATE DATETIME NOT NULL,
-> CON_ENDDATE DATETIME NOT NULL,
-> PUBLICATION_PUB_ID INT NOT NULL,
-> INDEX PUBLICATION (PUBLICATION_PUB_ID),
-> CONSTRAINT FK_CONTRACT_PUBLICATION FOREIGN KEY (PUBLICATION_PUB_ID) REFERENCES PUBLICATION (PUB_ID)) ;
Related
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.
i got these two succesfull queries:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
and
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
but when i try this one:
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code),
foreign key(condition_code) references Donors_Medical_Condition(condition_code) );
i get "Error Code: 1215, cannot add foreign key constraint"
i dont know what am i doing wrong.
In MySql, a foreign key reference needs to reference to an index (including primary key), where the first part of the index matches the foreign key field. If you create an an index on condition_code or change the primary key st that condition_code is first you should be able to create the index.
To define a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES tbl_name (index_col_name,...)
Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
KEY ( condition_code ), -- <---- this is newly added index key
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
But it seems you defined your tables order and references wrongly.
You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.
Modify your script accordingly.
They should be written as:
-- create parent table first ( general practice )
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code)
);
-- child table of Medical_Conditions
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code)
references Donors_Medical_Condition(condition_code)
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
A workaround for those who need a quick how-to:
FYI: My issue was NOT caused by the inconsistency of the columns’ data types/sizes, collation or InnoDB storage engine.
How to:
Download a MySQL workbench and use it’s GUI to add foreign key. That’s it!
Why:
The error DOES have something to do with indexes. I learned this from the DML script automatically generated by the MySQL workbench. Which also helped me to rule out all those inconsistency possibilities.It applies to one of the conditions to which the foreign key definition subject. That is: “MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.” Here is the official statement: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
I did not get the idea of adding an index ON the foreign key column(in the child table), only paid attention to the referenced TO column(in the parent table).
Here is the auto-generated script(PHONE.PERSON_ID did not have index originally):
ALTER TABLE `netctoss`.`phone`
ADD INDEX `personfk_idx` (`PERSON_ID` ASC);
ALTER TABLE `netctoss`.`phone`
ADD CONSTRAINT `personfk`
FOREIGN KEY (`PERSON_ID`)
REFERENCES `netctoss`.`person` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I think you've got your tables a bit backwards. I'm assuming that Donors_Medical_Condtion links donors and medical conditions, so you want a foreign key for donors and conditions on that table.
UPDATED
Ok, you're also creating your tables in the wrong order. Here's the entire script:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code) );
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code) references Medical_Conditions(condition_code) );
I got the same issue and as per given answers, I verified all datatype and reference but every time I recreate my tables I get this error. After spending couple of hours I came to know below command which gave me inside of error-
SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR
------------------------
2015-05-16 00:55:24 12af3b000 Error in foreign key constraint of table letmecall/lmc_service_result_ext:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "fk_SERVICE_RESULT_EXT_LMC_SERVICE_RESULT1" FOREIGN KEY ("FK_SERVICE_RESULT") REFERENCES "LMC_SERVICE_RESULT" ("SERVICE_RESULT") ON DELETE NO ACTION ON UPDATE NO ACTION
I removed all relation using mysql workbench but still I see same error. After spending few more minutes, I execute below statement to see all constraint available in DB-
select * from information_schema.table_constraints where
constraint_schema = 'XXXXX'
I was wondering that I have removed all relationship using mysql workbench but still that constraint was there. And the reason was that because this constraint was already created in db.
Since it was my test DB So I dropped DB and when I recreate all table along with this table then it worked. So solution was that this constraint must be deleted from DB before creating new tables.
Check that both fields are the same size and if the referenced field is unsigned then the referencing field should also be unsigned.
So I've been researching this for hours and been having no luck in finding something suitable for what I'm trying to do.
I'm currently having two issues: Creating a table with multiple foreign keys referencing the same primary key and splitting these attributes into multiple columns.
In the end, I would like my table to look something like this, where my O-Director_ID is the primary key in one column that correlates to all the other ID's (in this case FAD_ID, SAD_ID and SUD_ID) in the other column that are all foreign keys corresponding to the primary key from another table (Member_ID from crew_member, which already exists).
Here's what I'm currently trying to do, just to create multiple foreign keys (I don't even know how to go about creating that second column yet):
mysql> create table Other_Directing (
-> O_Director_ID int (4) not null auto_increment,
-> FAD_ID int (5) not null,
-> SAD_ID int (5) not null,
-> SUD_ID int <5> not null,
-> primary key (O_Director_ID),
-> foreign key (FAD_ID) references crew_member(Member_ID),
-> foreign key (SAD_ID) references crew_member(Member_ID),
-> foreign key (SUD_ID) references crew_member(Member_ID)
-> );
However even this doesn't work, I get this error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'<5> not null,
primary key (O_Director_ID),
foreign key (FAD_ID) references crew_'
at line 5
Thank you and I hope this makes sense.
Regards,
Michael
change SUD_ID int <5> not null,
to this: SUD_ID int (5) not null,
Does your project really necessitate non-default sizes on your int columns? If so, you have a typo... one of your sizes is in <>'s instead of ()'s: -> SUD_ID int <5> not null should be -> SUD_ID int (5) not null
If you're sure you do want the sizes due to memory constraints:
create table Other_Directing (
O_Director_ID int not null auto_increment,
FAD_ID int not null,
SAD_ID int not null,
SUD_ID int not null,
primary key (O_Director_ID),
foreign key (FAD_ID) references crew_member(Member_ID),
foreign key (SAD_ID) references crew_member(Member_ID),
foreign key (SUD_ID) references crew_member(Member_ID)
);
what is wrong?
mysql> create table price(
-> p_code char(1) not null,
-> p_description varchar(20),
-> p_rentfee decimal(2,2) not null,
-> p_dylatefee decimal(2,2));
Query OK, 0 rows affected (0.18 sec)
mysql> create table movie(
-> mv_no char(4) not null,
-> mv_name varchar(50) not null,
-> mv_year char(4) not null,
-> mv_cost decimal(2,2) not null,
-> mv_genre varchar(15) not null,
-> p_code char(1) not null,
-> foreign key (p_code) references price(p_code));
ERROR 1215 (HY000): Cannot add foreign key constraint
mysql>
price.p_code is not the primary key for price. Try:
create table price(
p_code char(1) not null PRIMARY KEY,
p_description varchar(20),
p_rentfee decimal(2,2) not null,
p_dylatefee decimal(2,2));
In general, foreign keys must reference a primary/unique key, a whole primary/unique key, and nothing but a primary/unique key.
In some RDBMS, for example SQL Server, you can reference a column with a unique index (not key) (see can we have a foreign key which is not a primary key in any other table?), but this is non-standard behavior.
Engine should be the same e.g. InnoDB
Datatype should be the same, and with same length. e.g. VARCHAR(20)
Collation Columns charset should be the same. e.g. utf8
Watchout: Even if your tables have same Collation, columns still could have different one.
Unique - Foreign key should refer to field that is unique (usually primary key) in the referenced table.
p_code should be a primary key in your price table:
create table price(
-> p_code char(1) not null,
-> p_description varchar(20),
-> p_rentfee decimal(2,2) not null,
-> p_dylatefee decimal(2,2),
-> PRIMARY KEY ( p_code ));
set p_code to be a key ,either set it to be a unique key or primary key.
The referenced column price.p_code must be unique (primary or unique key need to be created).
Both tables must be InnoDb tables, use ENGINE = INNODB in CREATE TABLE statement.
The data type for the child column must match the parent column exactly. For example, since price.p_code is an char(1), movie.p_code also needs to be an char(1) and price.p_code need be a Primary Key or need create a Index.