Hey guys getting an Error code 1215, SQL state HY000: Cannot add foreign key constraint for my PERSON_GROUP table and IMAGES table.. Don't know why, is there something wrong with my referencing? I've tried rewriting it but its just not working...
Updated code im now just getting an error for FOREIGN KEY (ID) REFERENCES INSTRUMENT(ID)
You can only create foreign keys that reference either the primary key or a unique key. Since ID is the primary key of PERSON change your foreign keys to point to ID instead of email. You could also make email a unique column, which is probably a good idea to make sure no one reuse the same email address, but it is still less storage to make foreign keys on an integer then a string.
I had this problem. The problem was database engine. Until i added the ENGINE=MyISAM DEFAULT CHARSET=latin1 before it worked. I guess my default was innoDB or something else.
CREATE TABLE LECTURE_NOTE (
ID bigint(20) NOT NULL,
NOTE VARCHAR(1000) NOT NULL,
NOTE_DATE TIMESTAMP NULL DEFAULT NULL,
LECTURE_ID bigint(20) NOT NULL,
PUBLISHER_ID bigint(20) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_lecture_id FOREIGN KEY (LECTURE_ID) REFERENCES
COURSE_LECTURE (ID),
CONSTRAINT fk_publisher_id FOREIGN KEY (PUBLISHER_ID) REFERENCES
PUBLISHER (ID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Related
I'm setting up a database for an informatics class using PHPMyAdmin (no SQL or anything, just putting it straight into PHPMyAdmin), and currently I'm trying to set a foreign key in one of my tables to a primary key in another table. I keep getting this error: Error creating foreign key on numberofGPUs (check data types). I realized that one was a TINYINT and one was an INT, so I changed it so they're both INT's. I also noticed one was signed and the other wasn't, so I made them both unsigned. The foreign key constraint name is unique (I even changed it just in case it wasn't), and I'm honestly at a loss right now as to why it's doing this. I've even gone so far as to delete one of the tables (the one with the primary key) and completely remake it, just to have the same issue. Any help would be super helpful.
Below is the SQL code for creating the RUNNING_GPUS table, which has the primary key numberofGPUs:
CREATE TABLE `RUNNING_GPUS` (
`rigID` varchar(12) NOT NULL,
`numberofGPUs` int(2) unsigned NOT NULL,
`runningGPUs` int(2) unsigned NOT NULL,
PRIMARY KEY (`rigID`,`numberofGPUs`),
KEY `rigID` (`rigID`),
CONSTRAINT `rig-fk-for-running` FOREIGN KEY (`rigID`) REFERENCES `RIGS` (`rigID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
Below is the SQL code for creating the RIGS table, which has the foreign key:
CREATE TABLE `RIGS` (
`rigID` varchar(12) NOT NULL,
`rigName` varchar(50) NOT NULL,
`osVersion` varchar(10) NOT NULL,
`numberofGPUs` int(2) unsigned NOT NULL,
`rigLocation` varchar(50) NOT NULL,
`lastPing` varchar(4) NOT NULL,
`lastReboot` varchar(4) NOT NULL,
`latestCrash` varchar(4) NOT NULL,
`lostRevenuePerHour` decimal(5,4) unsigned DEFAULT NULL,
`hardwareErrorType` varchar(100) DEFAULT NULL,
`hardwareErrorMean` decimal(7,3) unsigned DEFAULT NULL,
PRIMARY KEY (`rigID`),
CONSTRAINT `error-type-for-rigs` FOREIGN KEY (`hardwareErrorType`) REFERENCES `HARDWARE_ERRORS` (`hardwareErrorType`),
CONSTRAINT `revenue-for-rigs` FOREIGN KEY (`lostRevenuePerHour`) REFERENCES `LOST_REVENUES` (`lostRevenuePerHour`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
I'm also adding the foreign keys in through PHPMyAdmin, but when I tried to do the following code:
ALTER TABLE `RIGS`
ADD CONSTRAINT `test77`
FOREIGN KEY (`numberofGPUs`) REFERENCES `RUNNING_GPUS` (`numberofGPUs`);
it threw an error at me saying: #1005 - Can't create table aetrigg_db.RIGS (errno: 150 "Foreign key constraint is incorrectly formed")
ETA: I've been messing around with SQL Fiddle for a while now, and have all the tables in it. Everything works EXCEPT for this numberofGPUs. You can access the fiddle here: http://sqlfiddle.com/#!9/ec079e. I'm just adding the ALTER TABLE from above and adding it to the bottom, and it gets an error every time, saying that it can't add the foreign key. The RIGS table is the parent, and the RUNNING_GPUS is the child for the rigID column, but the RUNNING_GPUS is the parent and RIGS is the child for the numberofGPUs column. I tried to set it up by making the RIGS first, then the RUNNING_GPUS, and then altering the RIGS table, but that isn't working.
Swap the order in RUNNING_GPUS primary key
change
PRIMARY KEY (rigID,numberofGPUs),
to
PRIMARY KEY (numberofGPUs, rigID),
Foreign keys have to be a key themselves, of some sort, and apparently mysql doesn't consider secondary parts of a key to be of a key type.
I want to create table with foreign keys.
This is scheme of this table:
CREATE TABLE `SupplierOrderGoods` (
`shopOrder_id` INT(11) NOT NULL,
`supplierGood_id` INT(11) NOT NULL,
`count` INT(11) NOT NULL,
PRIMARY KEY (`shopOrder_id`, `supplierGood_id`),
CONSTRAINT `FK_SupplierOrderGoods_ShopOrders` FOREIGN KEY (`shopOrder_id`) REFERENCES `shoporders` (`id`),
CONSTRAINT `FK_SupplierOrderGoods_SupplierGoods` FOREIGN KEY (`supplierGood_id`) REFERENCES `suppliergoods` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
It has two links: to table SupplierGoods — FK_SupplierOrderGoods_SupplierGoods and to table ShopOrders — FK_SupplierOrderGoods_ShopOrders. When I execute this code either in HeidiSQL or in phpMyAdmin odd index FK_SupplierOrderGoods_SupplierGoods is being created.
I don't specify it in my scheme, but it is being created. I realized it when I had seen this in HeidiSQL:
Also, there are possibility to see create-code of the table in heidi:
CREATE TABLE `SupplierOrderGoods` (
`shopOrder_id` INT(11) NOT NULL,
`supplierGood_id` INT(11) NOT NULL,
`count` INT(11) NOT NULL,
PRIMARY KEY (`shopOrder_id`, `supplierGood_id`),
------> INDEX `FK_SupplierOrderGoods_SupplierGoods` (`supplierGood_id`),
CONSTRAINT `FK_SupplierOrderGoods_ShopOrders` FOREIGN KEY (`shopOrder_id`) REFERENCES `shoporders` (`id`),
CONSTRAINT `FK_SupplierOrderGoods_SupplierGoods` FOREIGN KEY (`supplierGood_id`) REFERENCES `suppliergoods` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
I didn't specify INDEX, but it is here. I am scared... Why ? :'(
Why this index appears? I think my heidi is broken, so tried in phpmyadmin, but got same result.
I thinked if it can be correct... but why only 1 index for only 1 field? Why not two indexes if it is correct?
Update
Wow! I just realized, that all tables with foreign key has index! I googled it and found this. So it it normal, that index is being created with fk, right?
Then, why only 1 index is being created, but not two???
im new on mysql workbench, and i tried so many things to put my script working but i simply cant... Ive got these tables:
CREATE TABLE Utilizador (email varchar(40) not null, nome varchar(50)
not null, dataNascimento date, profissao varchar(50) not null,
reputacao double(3,2) unsigned not null, constraint pk_Utilizador
primary key(email))
This is the first table created!
CREATE TABLE POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, coordenadaX int, coordenadaY int,
descricaoPOI varchar(200), constraint pk_POI primary key(email,
designacaoPOI), constraint fk_POI foreign key(email) references
Utilizador(email) on delete cascade)
This is the second table created!
CREATE TABLE Utilizador_POI (email varchar(40) not null, designacaoPOI
varchar(10) not null, constraint pk_Utilizador_POI primary key(email,
designacaoPOI), constraint fk1_Utilizador_POI foreign key(email)
references Utilizador(email) on delete cascade, constraint
fk2_Utilizador_POI foreign key(designacaoPOI) references
POI(designacaoPOI) on delete cascade)
This table gives me the error: Error Code: 1215. Cannot add foreign key constraint
I did some tests and im almost sure that the problem is in the foreign key "designacaoPOI". The other FK ("email") dont give me any error, so maybe the problem is in the Table POI?
Thanks in advanced!
The problem here is twofold:
1/ Use IDs for PRIMARY KEYs
You should be using IDs for primary keys rather than VARCHARs or anything that has any real-world "business meaning". If you want the email to be unique within the Utilizador table, the combination of email and designacaoPOI to be unique in the POI table, and the same combination (email and designacaoPOI) to be unique in Utilizador_POI, you should be using UNIQUE KEY constraints rather than PRIMARY KEY constraints.
2/ You cannot DELETE CASCADE on a FOREIGN KEY that doesn't reference the PRIMARY KEY
In your third table, Utilizador_POI, you have two FOREIGN KEYs references POI. Unfortunately, the PRIMARY KEY on POI is a composite key, so MySQL has no idea how to handle a DELETE CASCADE, as there is not a one-to-one relationship between the FOREIGN KEY in Utilizador_POI and the PRIMARY KEY of POI.
If you change your tables to all have a PRIMARY KEY of ID, as follows:
CREATE TABLE blah (
id INT(9) AUTO_INCREMENT NOT NULL
....
PRIMARY KEY (id)
);
Then you can reference each table by ID, and both your FOREIGN KEYs and DELETE CASCADEs will work.
I think the problem is that Utilizador_POI.email references POI.email, which itself references Utilizador.email. MySQL is probably upset at the double-linking.
Also, since there seems to be a many-to-many relationship between Utilizador and POI, I think the structure of Utilizador_POI isn't what you really want. Instead, Utilizador_POI should reference a primary key from Utilizador, and a matching primary key from POI.
The problem is in your second table. Your primary key is (email,designacaoPOI), when you try to reference that in your table it gives you error because of this:
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
For it to work, either change the order of your second tale PRIMARY KEY :
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email), -- changed the order
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
or add an index for designacaoPOI:
CREATE TABLE POI (
email VARCHAR(40) NOT NULL,
designacaoPOI VARCHAR(10) NOT NULL,
coordenadaX INT,
coordenadaY INT,
descricaoPOI VARCHAR(200),
CONSTRAINT pk_POI PRIMARY KEY (designacaoPOI,email),
KEY key_designacaoPOI(designacaoPOI), -- added index for that column
CONSTRAINT fk_POI FOREIGN KEY (email)
REFERENCES Utilizador(email) ON DELETE CASCADE
);
sqlfiddle demo
Either of these solutions will let you create your third table without errors.
I have an SQL statement :
CREATE TABLE RoomType(
hotelID SMALLINT NOT NULL,
name VARCHAR(20) NOT NULL,
PRIMARY KEY (hotelID, name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE BookingItem(
bookingID SMALLINT NOT NULL,
roomTypeName VARCHAR(20) NOT NULL,
PRIMARY KEY (bookingID, roomTypeName),
FOREIGN KEY (roomTypeName) REFERENCES RoomType(name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And it show errors #1215 - Cannot add foreign key constraint.
However when I change the line :
PRIMARY KEY (hotelID, name)
into
PRIMARY KEY (name, hotelID)
it works perfectly fine. I dont know what happens here. Can someone explain to me why this happens. Thank you very much.
FOREIGN KEY should match either several columns from left most part of the PRIMARY KEY or the PRIMARY KEY completely.
So in case of (hotelID, name) PK you can create a foreign key that refers to hotelID or to (hotelID, name), but not to name.
That's what documentation says about that:
However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
I am trying to design a database but I need some help with the relationships. Am i getting the table design right?
Here is the database idea..
User will submit a howto, each howto will have one or more steps associated with(a one to many). each step can have random pictures associated with(another one to many). so I am thinking of this:
CREATE TABLE `HowtoStepImage`
`id` int(10) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL,
`howto_id` varchar(25) NOT NULL,
`step_id` varchar(25) NOT NULL,
`img_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `hsi_k_1` (`howto_id`),
CONSTRAINT `hsi_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
CONSTRAINT `hsi_ibfk_2` FOREIGN KEY (`step_id`) REFERENCES `HowtoStep` (`step_id`),
CONSTRAINT `hsi_ibfk_3` FOREIGN KEY (`img_id`) REFERENCES `StepImage` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
table HowtoStep
step_id, title, content, created
primary key (step_id)
table StepImage
img_id, filename, created
CREATE TABLE `UserHowtoComment` (
`id` int(10) unsigned NOT NULL auto_increment,
`howto_id` varchar(25) NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`comment` varchar(500) NOT NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `UserHowtoComment_ibfk_1` (`howto_id`),
KEY `UserHowtoComment_ibfk_2` (`user_id`),
CONSTRAINT `UserHowtoComment_ibfk_1` FOREIGN KEY (`howto_id`) REFERENCES `HowtoStepImage` (`howto_id`),
CONSTRAINT `UserHowtoComment_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
however, I am getting error when creating the table, I am sure it is due to my database design. here is what mysql>SHOW ENGINE INNODB STATUS; shows:
091217 9:59:59 Error in foreign key constraint of table UserhowtoComment:
FOREIGN KEY (`howto_id`) REFERENCES `howtoStepImage` (`howto_id`),
CONSTRAINT `UserHowtoComment_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
the howto_id is a key(index) in UserHowtoComment though. I am not sure if that is the exact problem here..
Make 3 tables: one for HowTo, one for HowToStep, one for HowToStepImage.
Give each table a clearly defined key, e.g. a number or a string.
Then let the 'child' table refer to the key of the parent table.
Make sure that the columns have clear names as well.
TABLE HowTo
COLUMNS HowToId(key)
TABLE HowToStep
COLUMNS HowToStepId(key), HowToId
TABLE HowToStepImage
COLUMNS HowToStepImageId(key), HowToStepId
your query is really messy e.g. step_id varchar(25) needs to be an int.
why dont you just use a gui programm or maybe the good old phpMyAdmin, so you can learn the from the Querys they are creating, phpMyAdmin also has a advanced feature call "Designer" to create constraints.
If I read this correctly, your HowToComment id is a foreign key to HowtoStepImage. Does every comment have to have an image? Seems like a chicken and the egg issue. It seems, from your problem description, that an image links to a comment, not the other way around.
you're falling prey to the misleading terminology in MySQL. in the relational model, key is (necessarily) distinct. in the MySQL-speak, it's just an index. you need either PRIMARY KEY or UNIQUE KEY.
edit to add explicitly what is implied above: foreign keys must point to a key in the relational sense.