Error adding foreign keys in many to many relationship - mysql

having two tables : "personnes"
CREATE TABLE IF NOT EXISTS personnes(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
nom VARCHAR(40) NOT NULL,
PRIMARY KEY(id)
)ENGINE=InnoDB;
and "listadresses"
CREATE TABLE IF NOT EXISTS listadresses(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
adresse VARCHAR(40) NOT NULL,
PRIMARY KEY(id)
)ENGINE=InnoDB;
i'm unable to add a foreign key for each column based on the primary key of the children tables to reproduce a many to many relation, how could i achieve this behaviour
CREATE TABLE IF NOT EXISTS liaisons(
id_nom INT UNSIGNED NOT NULL ,
id_adresse INT UNSIGNED NOT NULL ,
CONSTRAINT fk_nom FOREIGN KEY(id_nom) REFERENCES personnes(id),
CONSTRAINT fk_adresse FOREIGN KEY(id_adresse) REFERENCES listeadresses(id),
PRIMARY KEY(id_nom,id_adresse)
)ENGINE=InnoDB;
instead i got error code 1215. cannot add foreign key constraint, thanks in advance for any insight !

Here's your problem :)
Instead of:
REFERENCES listeadresses(id),
try
REFERENCES listadresses(id),
It can't add the foreign key, as obviously listeadresses doesn't exist, but listadresses does.

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

Confusing cannot add foreign key constraint error

Ok, maybe it's late and I'm being stupid, but I can't seem to figure out why I'm getting a Cannot add Foreign Key Constraint error for the following query
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);
And yes, it is a database about noble titles... it's a long story
There is no column LordshipId in table People_Lordships.
Your foreign key definition attempts to reference a column that doesn't exist.
REFERENCES People_Lordships (`LordshipId`,`Id`)
^^^^^^^^^^^^
Figured this one out.
It turns out MySQL cannot add a foreign key constraint against a column that is not the first column in an index.
The following will work
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date,
INDEX Idx_LordshipId (LordshipId)
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);

SQLfiddle Errno: 150 - Foreign Key Issue

When I try to set a Foreign key, it throws the Error number 150.
Schema Creation Failed: Can't create table 'db_2_f856e.urlnames'
This is the code:
create table images(
id int auto_increment primary key
,gender varchar(6)
,pattern varchar(50)
,item_name varchar(25)
,url_id int(250)
)//
create table urlnames(
url_id_no int(250)
,url varchar(250)
,foreign key (url_id_no) references images(url_id)
)//
Can someone explain why it is not working?
Thanks
Your data structure doesn't make sense. I think you want:
create table urlnames(
url_id_no int auto_increment primary key,
url varchar(250)
);
create table images(
image_id int auto_increment primary key,
gender varchar(6),
pattern varchar(50),
item_name varchar(25),
url_id int(250) references urlnames(url_id_no)
);
Any column referenced by a foreign key reference needs to be a primary key or unique key. And, urlnames should have its id column declared as a primary key.
Here is a SQL Fiddle example.

errno 150 mySQL foreign key

This SQL is giving me Errno 150 when i'm trying to create the second table with the foreign key on UserID
Can anyone please advice me what am i doing wrong?
CREATE DATABASE IF NOT EXISTS OTA;
USE OTA;
CREATE TABLE IF NOT EXISTS Users
(
UserID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
UserName varchar(255) NOT NULL,
Email varchar(255) UNIQUE ,
PW varchar(255),
PN varchar(255),
Admin BIT
);
CREATE TABLE IF NOT EXISTS Notes
(
UID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
Note varchar (255) NOT NULL,
c_Date Date NOT NULL,
c_text varchar (255) NOT NULL,
FOREIGN KEY (UID) REFERENCES Persons(UserID)
);
Sorry for being a duplicate question but i can't find my answer between the related ones.
The problem is that you are trying to reference Persons(UserID) when your first table is called Users. Try this for your key:
FOREIGN KEY (UID) REFERENCES Users(UserID)
However, you should have a separate column for the note ID.
Try declaring the primary key after:
CREATE TABLE Orders
(O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))
Also, you auto-incremented both UID and UserID. This is fine if they are the same length, but if you try to reference a foreign key value that doesn't exist, you will get an error.

How can I add a foreign key when creating a new table?

I have these two CREATE TABLE statements:
CREATE TABLE GUEST (
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
);
CREATE TABLE PAYMENT (
id int(15) not null auto_increment
Foreign Key(id) references GUEST(id),
BillNr int(15) not null
);
What is the problem in the second statement? It did not create a new table.
The answer to your question is almost the same as the answer to this one .
You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using "references").
This has some code showing how to create foreign keys by themselves, and in CREATE TABLE.
Here's one of the simpler examples from that:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
I will suggest having a unique key for the payment table. On it's side, the foreign key should not be auto_increment as it refer to an already existing key.
CREATE TABLE GUEST(
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
) ENGINE=INNODB;
CREATE TABLE PAYMENT(
id int(15)not null auto_increment,
Guest_id int(15) not null,
INDEX G_id (Guest_id),
Foreign Key(Guest_id) references GUEST(id),
BillNr int(15) not null
) ENGINE=INNODB;
Make sure you're using the InnoDB engine for either the database, or for both tables. From the MySQL Reference:
For storage engines other than InnoDB,
MySQL Server parses the FOREIGN KEY
syntax in CREATE TABLE statements, but
does not use or store it.
create table course(ccode int(2) primary key,course varchar(10));
create table student1(rollno int(5) primary key,name varchar(10),coursecode int(2) not
null,mark1 int(3),mark2 int(3),foreign key(coursecode) references course(ccode));
There should be space between int(15) and not null