MySQL error: Cannot add foreign key constraint? - mysql

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

Related

Why does it fail to open the referenced table if it already exists?

Somehow I can't create a join table for two entities I already have.
Here is what I run on MySQL just fine, the last one is the one I'm struggling with.
create table instructor_detail_table(
instructor_detail_id int not null primary key auto_increment,
instructor_class varchar(40) not null
);
create table instructor_table(
instructor_id int not null primary key auto_increment,
instructor_name varchar(40) not null,
instructor_detail_id int not null,
foreign key (instructor_detail_id) references instructor_detail_table (instructor_detail_id)
);
create table course_table(
course_id int not null primary key auto_increment,
course_class varchar(40) not null,
instructor_id int not null,
foreign key (instructor_id) references instructor_table (instructor_id)
);
create table student_table(
student_id int not null primary key auto_increment,
student_name varchar(40) not null,
student_age int not null
);
create table student_course_table(
student_id int not null,
course_id int not null,
foreign key (student_id) references student_table (student_id),
foreign key (course_id) references course_table (course_id),
primary key (student_id, course_id)
);
When I try to create the student_course_table MySQL complaints it can't open the referenced table student_table
Thanks in advance
You can have this problem if the storage engine is not the good one.
For example 'MyISAM' instead of 'InnoDB' for the table 'student_table'.
Because MyISAM doesn't support foreign key.

#1005 - Can't create table `musicplayer`.`Albums` (errno: 150 "Foreign key constraint is incorrectly formed")

I'm trying to define some tables with SQL, but when I execute it I have an error. Below there is my code and the error which I receive.
CREATE TABLE Artists
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
description VARCHAR(255)
);
CREATE TABLE Albums
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
releasedate DATE,
artistid INT,
genreid INT,
picture VARCHAR(255),
CONSTRAINT `fk_albums_artists`
FOREIGN KEY (artistid) REFERENCES Artists(id),
CONSTRAINT `fk_albums_genres`
FOREIGN KEY (genreid) REFERENCES Genres(id)
);
CREATE TABLE Tracks
(
id INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
playtime INT NOT NULL,
albumid INT,
CONSTRAINT `fk_tracks_album`
FOREIGN KEY (albumid) REFERENCES Albums(id)
);
CREATE table Genres
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL
);
Error in my SQL query:
MySQL said: Documentation
1005 - Can't create table musicplayer.Albums (errno: 150 "Foreign
key
constraint is incorrectly formed") (Details…)
Declare the tables in order, so the tables are defined before they are referenced:
CREATE TABLE Artists (
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
description varchar(255)
);
CREATE table Genres(
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null
);
CREATE TABLE Albums (
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
releasedate date,
artistid int,
genreid int,
picture varchar(255),
CONSTRAINT `fk_albums_artists` FOREIGN KEY (artistid) REFERENCES Artists(id),
CONSTRAINT `fk_albums_genres` FOREIGN KEY (genreid) REFERENCES Genres(id)
);
CREATE TABLE Tracks(
id int(11) AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
playtime int not null,
albumid int,
CONSTRAINT `fk_tracks_album` FOREIGN KEY (albumid) REFERENCES Albums(id)
);
Here is a db<>fiddle.
You can still have tables that reference each other. However, you will need to declare such foreign key constraints using ALTER TABLE rather than in the CREATE TABLE statement. However, you do not need to do this for these table definitions.

Mysql foreign key errors can't fix

I am new to mysql, and writing a sql script from a mysql database, most of my tables work, but some won't, and the mysql error is about as nondescript as possible. It might be something to do with multiple foreign keys.
create table Users (
id int not null auto_increment,
type enum('t1', 't2', 't3') not null,
name char(30) not null,
phone char(15),
email char(30),
username char(30),
password char(30),
created timestamp,
primary key (id)
);
create table Groups (
id int not null auto_increment,
user int not null,
name char(30) not null,
phone char(15),
email char(30),
created timestamp,
primary key (id),
foreign key (user) references Users(id)
);
create table Group_Members (
id int not null auto_increment,
group int not null,
user int not null,
created timestamp,
primary key (id),
foreign key (group) references Groups(id),
foreign key (user) references Users(id)
);
Group is reserved word in MySQL. You have to use ` to quote reserved words in your queries.
Try this:
create table Users (
id int not null auto_increment,
type enum('t1', 't2', 't3') not null,
name char(30) not null,
phone char(15),
email char(30),
username char(30),
password char(30),
created timestamp,
primary key (id)
);
create table Groups (
id int not null auto_increment,
user int not null,
name char(30) not null,
phone char(15),
email char(30),
created timestamp,
primary key (id),
foreign key (user) references Users(id)
);
create table Group_Members (
id int not null auto_increment,
`group` int not null,
user int not null,
created timestamp,
primary key (id),
foreign key (`group`) references Groups(id),
foreign key (user) references Users(id)
);

Cannot add foreign key here?

So I'm trying to create tables and I can't for the life of me understand why i keep getting and error saying "Cannot add foreign key to constraint".
The types are the same, the parent is a primary key, and they're NULLness is the same.
The problem is in the line in the create table for CDSingers where it says:
foreign key (track_num) references CDTracks (track_num),
(it's near the end)
It's the only table that won't be created and it's because of this line.
Please help.
(some of the other tables have been ommitted since they aren't connected)
create table CD
(
num int NOT NULL,
producer varchar(100) NOT NULL,
cd_number varchar(100) NOT NULL,
title varchar(100) NOT NULL,
type varchar(100) ,
band_name varchar(100) ,
production_date DATE NOT NULL,
price double CHECK (price >= 0),
foreign key (type) references MusicType (type),
foreign key (band_name) references Band (band_name),
primary key (num),
unique (producer, cd_number)
);
create table CDTracks
(
num int NOT NULL,
track_num int NOT NULL,
song_name varchar(100) NOT NULL,
minute int NOT NULL,
foreign key (num) references CD (num),
primary key (num, track_num)
);
create table Singer
(
id int NOT NULL,
singer_firstname varchar(100) NOT NULL,
singer_lastname varchar(100) NOT NULL,
primary key (id)
);
create table CDSingers
(
num int NOT NULL,
track_num int NOT NULL,
singer_id int NOT NULL,
foreign key (num) references CDTracks (num),
foreign key (track_num) references CDTracks (track_num),
foreign key (singer_id) references Singer (id),
primary key (num, track_num, singer_id)
);
You declare composite foreign keys like this:
foreign key (num, track_num) references CDTracks (num, track_num),

MySQL error:1251 cannot add foreign key

The first 4 table are created fine, the transactions tables run into problem. I get the 1215 error: cannot add foreign key. I've checked an rechecked the data types, and made sure all FK are PK of their own tables. What's wrong here?
CREATE SCHEMA FinalDB;
CREATE TABLE `User` (
userId int not null auto_increment primary key,
first_name varchar(255) not null,
last_name varchar(255) not null,
address varchar(255) null,
DOB date not null,
availableBalance int not null default 0,
currency varchar(20)
);
CREATE TABLE Verifications(
userId int not null primary key,
passport int null,
ssn int null,
license int null,
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Linked_Account(
account_Id int not null,
userId int not null,
routing int null,
swift int null,
primary key (userId, account_Id),
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Wallet (
userId int not null,
walletId varchar(5) not null,
coinAmount int not null default 0,
netWorth int not null default 0,
primary key(userId, walletId),
constraint
foreign key (userId)
references `User`(userId)
);
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (walletId)
references Wallet(walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (payment_method)
references Linked_Account(account_id)
);
CREATE TABLE TransactionsExchange(
transactionId int not null auto_increment primary key,
userId int not null,
currencyFrom int not null,
currencyFromAmount int not null,
currencyInto int not null,
currencyIntoEquivalent int not null,
notes varchar(200) null,
`date` date not null,
constraint
foreign key (userId)
references User(userId),
constraint
foreign key (currencyFrom)
references Wallet(walletId),
constraint
foreign key (currencyInto)
references Wallet(walletId)
);
I've look online for possible answer, but it's usually having to do with inconsistent data types or undeclared PK's. I'm basically trying to make a transactions table to log various different data in different compositions. Using backend logic to handle what is required and what is not, aside from a few defaults.
To use a compound Primary Key as Foreign Key, you'll have to add the
same number of columns (that compose the PK) with same datatypes to
the child table and then use the combination of these columns in the
FOREIGN KEY definition.
see related post here https://stackoverflow.com/a/10566463/4904726
Try this 'Transactions' table creating query:
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, walletId)
references Wallet(userId, walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, payment_method)
references Linked_Account(userId, account_id)
);