Mysql foreign key errors can't fix - mysql

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

Related

errno: 150 "Foreign key constraint is incorrectly formed - mysql

I am trying to create a database for a school project. I am getting the error specified in the title, and cannot figure out how to resolve it. I am not very experienced in mySQL but apparently the error is vague and can be a number of thing. It happens when I try to input the showing table.
`CREATE TABLE Complex(
name varchar(50) not null,
streetNum integer,
streetName varchar(50),
city varchar(50),
province varchar(50),
postalCode char(6),
numTheatres integer,
primary key(name)
);
CREATE TABLE Theatre(
complexName varchar(50) not null,
theatreNum integer not null,
maxSeats integer,
screenSize varchar(6),
foreign key (complexName) references Complex(name),
primary key (complexName, theatreNum)
);
CREATE TABLE Supplier(
compName varchar(50) not null,
streetName varchar(50),
streetNum varchar(50),
city varchar(50),
province varchar(50),
postalCode char(6),
phone char(10),
contactFName varchar(10),
contactLName varchar(10),
primary key (compName)
);
CREATE TABLE Movie(
title varchar(100) not null,
runningTime integer,
rating varchar(4),
synopsis varchar(500),
director varchar(100),
prodComp varchar(100),
supplierName varchar(100),
startDate date,
endDate date,
foreign key (supplierName) references Supplier(compName),
primary key (title)
);
Create Table Actor(
fName varchar(50) not null,
lName varchar(50) not null,
primary key (fName,lName)
);
create table Stars
(
fName varchar(100) not null references Actor(fName),
lName varchar(100) not null references Actor(lName),
title varchar(100) not null references Movie(title),
primary key (fName, lName, title)
);
CREATE TABLE Account(
accountNum integer not null AUTO_INCREMENT,
password varchar(50) not null,
fName varchar(50),
lName varchar(50),
phone char(10),
email varchar(50),
creditCard varchar(15),
cardExpiry char(4),
primary key (accountNum)
);
CREATE TABLE Showing(
complexName varchar(50) not null,
title varchar(100) not null,
theatreNum integer not null,
startTime time not null,
seatsAvailable integer,
foreign key (complexName) references Theatre(complexName),
foreign key (title) references Movie(title),
foreign key (theatreNum) references Theatre(theatreNum),
primary key (startTime)
);
CREATE TABLE Review(
title varchar(100) not null,
ID integer not null,
score integer,
primary key (ID),
foreign key (title) references Movie(title)
);
CREATE TABLE Reserved(
accountNum integer not null,
complexName varchar(50) not null,
theatreNum integer not null,
movieTitle varchar(50) not null,
startTime time not null,
ticketsNum integer,
foreign key (accountNum) references Account(accountNum),
foreign key (complexName) references Showing(compName),
foreign key (theatreNum) references Showing(theatreNum),
foreign key (movieTitle) references Showing(movieTitle),
foreign key (startTime) references Showing(startTime),
primary key (accountNum, complexName, theatreNum, movieTitle, startTime)
)
;`
This is one of the most common misunderstandings about foreign keys for beginners.
CREATE TABLE Theatre(
complexName varchar(50) not null,
theatreNum integer not null,
primary key (complexName, theatreNum)
CREATE TABLE Showing(
complexName varchar(50) not null,
theatreNum integer not null,
foreign key (complexName) references Theatre(complexName),
foreign key (theatreNum) references Theatre(theatreNum),
...
When you reference a table with a multi-column primary key, your foreign key must be multi-column as well. Don't declare two foreign key constraints. Declare one foreign key constraint with the same columns as the primary key it references.
CREATE TABLE Showing(
complexName varchar(50) not null,
theatreNum integer not null,
foreign key (complexName, theatreNum) references Theatre(complexName, theatreNum),
...
For more tips on foreign key, like a checklist of what needs to be true, see the top answer on this question: MySQL Creating tables with Foreign Keys giving errno: 150

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

Why can't I add foreign key constraints

this is my code:
CREATE DATABASE exams;
SHOW DATABASES;
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(40),
last_name VARCHAR(40)NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE(email));
SHOW table status
INSERT INTO exams_3121(student_id, first_name, middle_name, last_name, email, password, reg_date)
CREATE TABLE entries
(
entrie_id int NOT NULL,
student_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (subject_id)REFERENCES subject(subject_id)
)
CREATE DATABASE subjects;
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(20) NOT NULL,
level_entery VARCHAR(40)NOT NULL,
exam_board VARCHAR(60) NOT NULL,
PRIMARY KEY (subject_id));
CREATE TABLE entries
(
entrie_id int NOT NULL,
entrie_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (subject_id)REFERENCES subject(subject_id)
)
When I use this code it says cannot add foreign key constraint
and I don't know what to do. Please and thanks in advance.
There are two problems.
First, you got the names of the table you're referencing wrong. The name of the tables are students and subjects, but you wrote student and subject.
Second, the entries table has two entrie_id columns. One of them should be student_id.
CREATE TABLE entries
(
entrie_id int NOT NULL,
student_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id)
)
Also, if you're creating multiple databases and putting your tables in them, you'll need to refer to tables with their database prefixes if they're different from the one you selected as default with the USE command. As you've written it, you're not actually using the databases you created with CREATE DATABASE.

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

How can I implement graph database with MySQL?

I want to implement connection as friends of friends using MySQL
CREATE TABLE user (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
email VARCHAR(60) NOT NULL,
....
PRIMARY KEY (id)
);
CREATE TABLE friendof (
user_a_id MEDIUMINT NOT NULL,
user_b_id MEDIUMINT NOT NULL,
PRIMARY KEY(user_a_id, user_b_id),
FOREIGN KEY(user_a_id) REFERENCES user(id),
FOREIGN KEY(user_b_id) REFERENCES user(id),
KEY reverseLookup (user_b_id),
KEY lookup (user_a_id),
);
Was that really so hard?