Foreign Key Unexpected - mysql

I'm using MySQL workbench and I am trying to create a table consist of foreign key using SQL Query. I am having problem with the Foreign part.
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int foreign key references employee_profile(eID)
)

Your syntax is wrong. Try:
create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (keyname) references employee_profile(eID)
)
For more information see the mysql documentation

create table employee_position
(
ePID int primary key,
ePName varchar(45) not null,
eID int,
foreign key (eID) references employee_profile(eID)
)
SQLFiddle demo

Check FOREIGN KEYS in MySQL.
Try this:
CREATE TABLE employee_position
(
ePID INT NOT NULL AUTO_INCREMENT,
ePName VARCHAR(45) NOT NULL,
eID INT NOT NULL,
PRIMARY KEY (ePID),
KEY CustomerID (eID),
CONSTRAINT FK_employee_position_EP
FOREIGN KEY (eID)
REFERENCES employee_profile (eID) ON DELETE CASCADE ON UPDATE CASCADE
);

Related

i am trying to create foreign keys but i got error 1822 .. please see my code below

CREATE TABLE employee(
empid int auto_increment primary key,
empfirstname varchar(200) not null,
emplastname varchar(200) not null,
email varchar(200) not null,
officenumber int not null
);
CREATE TABLE customer(
custid int auto_increment primary key,
firstname varchar(200) not null,
lastname varchar(200) not null,
address varchar(200) not null,
contact varchar(200)
);
CREATE TABLE product(
productid int auto_increment primary key,
productdesc varchar(500) not null,
weight int not null,
unit_cost int not null
);
CREATE TABLE productorder(
productid int,
orderid int,
primary key(productid,orderid),
constraint fk3 foreign key (productid) references product(productid),
constraint fk4 foreign key (orderid) references productorder(orderid)
);
CREATE TABLE salesorder(
salesorderid int auto_increment primary key,
empid int not null,
custid int not null,
orderdate date not null,
shippingmethod varchar (200) not null,
constraint a_fk1 foreign key (empid) references employee(empid),
constraint a_fk2 foreign key (custid) references customer(custid)
);
What is this meant to do?:
constraint fk4 foreign key (orderid) references productorder(orderid)
It's not uncommon for a table to have a foreign key back to its own primary key, such as for records which have a parent/child relationship. But that doesn't seem to be the case here.
More to the point of the error though, this isn't referencing the entire primary key for the target table. That key has two fields:
primary key(productid,orderid)
So the DBMS can't create the foreign key because its structure doesn't match the target primary key.
If you want to create that foreign key, it would need to match. Probably something like this:
constraint fk4 foreign key (productid,orderid) references productorder(productid,orderid)
But it doesn't appear that you need that foreign key at all, because it doesn't seem to make sense in your data model. Instead I suspect orderid might need to be autoincrement and just use the productid foreign key. Something like this:
CREATE TABLE productorder(
orderid int auto_increment primary key,
productid int,
constraint fk3 foreign key (productid) references product(productid)
);
(Note that there could be more changes you'd want to make to your data model. This answer doesn't purport to provide you with a complete production-ready data model, just to correct the error. Your data model is likely to change/evolve as you develop your system.)
Its normal,
The foreign key in table **productorder**
is refereing to the table itself:
constraint fk4 foreign key (orderid) references **productorder**(orderid)
In order to achieve the self-referencing constraint on the table productorder, you need to add another column with the same type and make typical referencing.
For instance :
Create table productorder (
productid int,
orderid int,
orderid_parent int,
primary key(productid,orderid),
constraint fk_self foreign key(orderid) references productorder(orderid_parent)
)

MySQL Error "Can't create table" Foreign Key Constraint

I'm trying to create a database using MySQL and having difficulties with my code. I created the base table with one attribute that I plan on using as a foreign key in another table but an error message comes up saying I cannot create the table. I only want help with creating that table as I know how to insert data.
create database aerogames_table;
CREATE TABLE
O_DETAILS
(
B_Number INT NOT NULL,
B_Name VARCHAR(60) NOT NULL,
Order_ID INT NOT NULL,
Order_CName VARCHAR(50) NOT NULL
)
engine=innodb;
CREATE TABLE
P_DETAILS
(
PRO_ID INT NOT NULL PRIMARY KEY,
Order_ID INT NOT NULL,
CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
PRO_Seller VARCHAR (50) NOT NULL,
PRO_Name VARCHAR (50) NOT NULL,
PRO_Year INT NOT NULL,
PRO_Price INT NOT NULL
)
engine=innodb;
1005 - Can't create table 'aerogames_table.p_details' (errno: 150)
Due to this https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
[CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
Foreign key need to reference to index column (no need to be primary key) so you need to create index on O_DETAILS.Order_ID like this
CREATE TABLE
O_DETAILS
(
B_Number INT NOT NULL,
B_Name VARCHAR(60) NOT NULL,
Order_ID INT NOT NULL,
Order_CName VARCHAR(50) NOT NULL,
KEY (Order_ID)
)
engine=innodb;
CREATE TABLE
P_DETAILS
(
PRO_ID INT NOT NULL PRIMARY KEY,
Order_ID INT NOT NULL,
CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
PRO_Seller VARCHAR (50) NOT NULL,
PRO_Name VARCHAR (50) NOT NULL,
PRO_Year INT NOT NULL,
PRO_Price INT NOT NULL
)
engine=innodb;
Certainly if you make O_DETAILS.Order_ID to be primary key, it will also create for you and this works

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`)
);

MySQL error: Cannot add foreign key constraint?

There always be the error:"Cannot add foreign key constraint" when I create my last table.
System: Mac OS X 10.9
DB : MySQL 5.6.14
DBM : Sequel Pro
CREATE TABLE users (
uid INT AUTO_INCREMENT PRIMARY KEY,
uname VARCHAR(20) NOT NULL,
uemail VARCHAR(20) NOT NULL,
ucity VARCHAR(20),
upassw VARCHAR(20) NOT NULL
);
CREATE TABLE songs(
sid INT AUTO_INCREMENT PRIMARY KEY,
sname VARCHAR(20) NOT NULL,
srldate DATE NOT NULL
);
CREATE TABLE albums (
albid INT AUTO_INCREMENT PRIMARY KEY,
albname VARCHAR(20) NOT NULL,
albrldate DATE NOT NULL,
albrltime TIME NOT NULL
);
CREATE TABLE artists (
aid INT AUTO_INCREMENT PRIMARY KEY,
aname VARCHAR(20) NOT NULL
);
CREATE TABLE genres (
gid INT AUTO_INCREMENT PRIMARY KEY,
gname VARCHAR(20) NOT NULL
);
CREATE TABLE playlists (
uid INT NOT NULL,
sid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, sid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(sid) REFERENCES songs(sid)
);
CREATE TABLE u_like_a (
aid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(aid, uid),
FOREIGN KEY(aid) REFERENCES artists(aid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE be_fan (
aid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(aid, uid),
FOREIGN KEY(aid) REFERENCES artists(aid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE follow (
uid INT NOT NULL,
to_uid INT NOT NULL,
PRIMARY KEY(uid, to_uid),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(to_uid) REFERENCES users(uid)
);
CREATE TABLE u_like_g (
gid INT NOT NULL,
uid INT NOT NULL,
PRIMARY KEY(gid, uid),
FOREIGN KEY(gid) REFERENCES genres(gid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
CREATE TABLE u_share_pl(
uid INT NOT NULL,
from_uid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, from_uid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(from_uid) REFERENCES users(uid),
FOREIGN KEY(plname) REFERENCES playlists(plname),
FOREIGN KEY(plmdate) REFERENCES playlists(plmdate),
FOREIGN KEY(plmtime) REFERENCES playlists(plmtime)
); #####---> This is the last table.
ERROR comes from here. I really don't why.
I have check the type for all attributes. The type and name of attributes have no problem.
But the mysql always say "Cannot add foreign key constraint"
Here is you reference wrong forgien REFERENCES users(from_uid) in last table.
FOREIGN KEY(from_uid) REFERENCES users(from_uid)
from_uid not belong to users
This should be
FOREIGN KEY(from_uid) REFERENCES users(uid)
your playLists table has primary key combination of four columns, so you should supply all these four columns as forieng key in u_share_pl table.
Another composite key as a reference should be a single constraint like
FOREIGN KEY(from_uid,sid,plname,plmdate,plmtime) REFERENCES playlists(uid,sid,plname,plmdate,plmtime)
Your last table Create should be:
CREATE TABLE u_share_pl(
uid INT NOT NULL,
from_uid INT NOT NULL,
sid INT NOT NULL,
plname VARCHAR(20) NOT NULL,
plmdate DATE NOT NULL,
plmtime TIME NOT NULL,
PRIMARY KEY(uid, from_uid, plname, plmdate, plmtime),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(from_uid,sid,plname,plmdate,plmtime) REFERENCES playlists(uid,sid,plname,plmdate,plmtime)
);

Can two columns from one table have a foreign key to the same column in another table?

I have two tables in a database, Person and Pet.
CREATE TABLE Person (
id INT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner)
REFERENCES Person(id),
FOREIGN KEY (current_owner)
REFERENCES Person(id)
)
I am trying to reference the previous owner, and the current owner for each pet. I have also tried
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id, id)
)
and
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id)
)
but I get the following error:
Error Code: 1215. Cannot add foreign key constraint
Is this even possible to accomplish? Or would I have to create some sort of bridge table to accommodate this?
Please try the following:
CREATE TABLE IF NOT EXISTS `pet` (
`id` int(11) NOT NULL,
`original_owner` int(11) NOT NULL,
`current_owner` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `origin` (`original_owner`),
KEY `current` (`current_owner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `pet`
ADD CONSTRAINT `pet_ibfk_2` FOREIGN KEY (`current_owner`) REFERENCES `person` (`id`),
ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`original_owner`) REFERENCES `person` (`id`);
The problem was the order I had the tables defined in the script. I had Pet come before Person. Once I put Person above Pet it worked fine. The example in the question was written from my head, as I didn't have the actual code handy when I posted it.