MySQL error:1251 cannot add foreign key - mysql

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

Related

What Can I replace 'IDENTITY' with to make this work?

Create Table Customer(
CustomerID Int NOT NULL IDENTITY (1,1) ,
LastName Char(25) NOT NULL,
FirstName Char(25) NOT NULL,
EmailAddress VarChar(100) NOT NULL,
EncryptedPassword VarChar(50) NULL,
Phone Char(12) NOT NULL,
StreetAddress Char(35) NULL
City Char(35) NULL DEFAULT 'Dallas',
[State] Char(2) NULL DEFAULT 'TX',
ZIP Char(10) NULL DEFAULT '75201',
CONSTRAINT CUSTOMER_PK PRIMARY KEY(CUSTOMERID),
CONSTRAINT CUSTOMER_EMAIL UNIQUE(EMAILADDRESS)
) ;
CREATE TABLE SEMINAR(
SeminarID INT NOT NULL IDENTITY (1, 1),
SeminarDate Date NOT NULL,
SeminarTime Time NOT NULL,
Location VarChar(100) NOT NULL,
SeminarTitle VarChar(100)
CONSTRAINT SEMINAR_PK PRIMARY KEY(SeminarID)
) ;
Create Table SEMINAR_CUSTOMER(
SeminarID Int NOT NULL,
CustomerID Int NOT NULL,
CONSTRAINT S_C_PK PRIMARY KEY(SeminarID, CustomerID),
CONSTRAINT S_C_SEMINAR_FK FOREIGN KEY(SeminarID)
REFERENCES SEMINAR(SeminarID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
CONSTRAINT S_C_CUSTOMER_FK FOREIGN KEY (CustomerID)
REFERENCES CUSTOMER(CustomerID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
) ;
CREATE TABLE CONTACT(
CustomerID Int NOT NULL,
ContactNumber Int NOT NULL,
ContactDate Date NOT NULL,
ContactType VarChar(30) NOT NULL,
SeminarID Int NULL,
CONSTRAINT CONTACT_PK PRIMARY KEY(CustomerID, ContactNumber),
CONSTRAINT CONTACT_ContactType
CHECK (ContactType IN ('Seminar',
'WebAccountCreation', 'WebPurchase',
'EmailAccountMessage', 'EmailSeminarMessage',
'EmailPurcahseMessage',
'EmailMessageExchange', 'FormLetterSeminar',
'PhoneConversation')),
CONSTRAINT CONTACT_SEMINAR_FK FOREIGN KEY(SeminarID)
REFERENCES SEMINAR(SeminarID)
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT CONTACT_SEMINAR_FK FOREIGN KEY(SeminarID)
REFERENCES SEMINAR(CustomerID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
);
CREATE TABLE PRODUCT(
ProductNumber Char(35) NOT NULL,
ProductType Char(24) NOT NULL,
ProductDescription VarChar(100) NOT NULL,
UnitPrice Numeric(9,2) NOT NULL
QuantityOnHand Int NULL
CONSTRAINT PRODUCT_PK PRIMARY KEY(ProductNumber),
CONSTRAINT PRODUCT_ProductType
CHECK (ProductType) IN ('Video',
'Video Companion', 'Book'))
);
CREATE TABLE INVOICE(
InvoiceNumber Int NOT NULL IDENTITY (35000, 1),
InvoiceDate Date NOT NULL,
CustomerID Int NOT NULL,
PaymentType Char(25) NOT NULL DEFAULT 'Cash',
SubTotal Numeric(9,2) NULL,
Shipping Numeric(9,2) NULL,
Tax Numeric(9,2) NULL,
Total Numeric(9,2) NULL,
CONSTRAINT INVOICE_PK PRIMARY KEY (InvoiceNumber),
CONSTRAINT INVOICE_PaymentType
CHECK (PaymentType IN ('VISA',
'MasterCard', 'American Express',
'PayPal', 'Check', 'Cash')),
CONSTRAINT INVOICE_CUSTOMER_FK FOREIGN KEY(CustomerID)
REFERENCES CUSTOMER(CustomerID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
);
CREATE TABLE LINE_ITEM(
InvoiceNumber Int NOT NULL,
LineNumber Int NOT NULL,
ProductNumber Char(35) NOT NULL,
Quantity Int NOT NULL
UnitPrice Numeric(9,2) NULL
Total Numeric(9,2) NULL
CONSTRAINT LINE_ITEM_PK PRIMARY KEY (InvoiceNumber, LineNumber),
CONSTRAINT L_I_INVOICE_FK FOREIGN KEY (InvoiceNumber)
REFERENCES INVOICE(InvoiceNumber)
ON UPDATE NO ACTION
ON DELETE NO ACTION
CONSTRAINT L_I_PRODUCT_FK FOREIGN KEY (ProductNumber)
REFERENCES Product (ProductNumber)
ON UPDATE NO ACTION
ON DELETE NO ACTION
);
There is my entire code. Copied directly from the book for a class. My professor will not help me, so I am hoping here would be kind enough to help. I have done nothing but work on this the last 3 days. This is the error message I keep getting for all the 'IDENTITY':
IDENTITY is not valid input at this position, expecting: ')'
Please help, I need this today.

MYSQL MULTIPLE FOREAIGN KEYS getting Cannot add foreign key constraint

CREATE TABLE customer (
customer_id INT NOT NULL,
last_name VARCHAR(25) NOT NULL,
first_name VARCHAR(25) NOT NULL,
street_address VARCHAR(25) NOT NULL,
apt_number INT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(2) NOT NULL,
zip_code INT NULL,
home_phone VARCHAR(12) NOT NULL,
mobile_phone VARCHAR(12) NULL,
other_phone VARCHAR(12) NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE donut_order(
donut_order_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
special_handling_notes VARCHAR(255) NULL,
PRIMARY KEY(donut_order_id),
FOREIGN KEY (customer_id)
REFERENCES customer (customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
CREATE TABLE donut_order_item (
donut_order_id INT NOT NULL,
donut_id INT NOT NULL,
qty INT NOT NULL,
PRIMARY KEY(donut_order_ID, donut_id),
UNIQUE INDEX(donut_id, donut_order_id),
CONSTRAINT donut_order FOREIGN KEY (donut_order_id)
REFERENCES donut_order (donut_order_id)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT donut FOREIGN KEY (donut_id)
REFERENCES donut (donut_id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
Try to use user Interface Instead and it could help you to solve this problem.
like this one:

#1005 - Can't create table 'EmployeeShifts' (errno: 150)

Here is the code below, I'm not sure what this error means...
All I know is that it has something to do with the employeeshifts table.
Does it have something to do with foreign keys?
(insterting this text as I have nothing else to say, but stack requires a lot of text)
CREATE TABLE Customer (
CustomerID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
Phone VARCHAR(45) NULL,
CustomerAddress VARCHAR(45) NOT NULL,
PRIMARY KEY (CustomerID));
CREATE TABLE Location (
Address VARCHAR(100) NOT NULL,
Latitude VARCHAR(45) NULL DEFAULT ' ',
Longitude VARCHAR(45) NULL,
PRIMARY KEY (Address));
CREATE TABLE Employee (
EmployeeID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
PRIMARY KEY (EmployeeID));
CREATE TABLE Truck (
LicensePlate CHAR(20) NOT NULL,
color VARCHAR(45) NULL,
capacity VARCHAR(45) NULL,
PRIMARY KEY (LicensePlate));
CREATE TABLE Shifts (
ShiftTime DATETIME NOT NULL,
PRIMARY KEY (ShiftTime));
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking VARCHAR(90) NOT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking, DateOfShift),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(Name),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime));
CREATE TABLE Reservation (
ReservNum INT NOT NULL,
ReserveDate DATE NULL,
PickupTime VARCHAR(45) NOT NULL,
NumOfPassengers INT NULL,
sheduledTime VARCHAR(45) NULL,
ActualPickupTime VARCHAR(45),
ActualTime VARCHAR(45),
PricePaid VARCHAR(45),
DriverHourlyRate DECIMAL(7,2) NOT NULL,
PassEmployeeHourlyRate DECIMAL (7,2) NOT NULL,
DriverSalary VARCHAR(10),
PassEmployeeSalary VARCHAR(10),
Customer_CustomerID INT,
Truck_LicensePlate char(20) NOT NULL,
Employee_EmployeeID_Driver INT,
Location_Address_Pickup VARCHAR(100),
Employee_EmployeeID_Passenger INT,
Location_Address_Drop VARCHAR(100),
PRIMARY KEY (ReservNum),
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
FOREIGN KEY (Truck_LicensePlate) REFERENCES Truck (LicensePlate),
FOREIGN KEY (Employee_EmployeeID_Driver) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Pickup) REFERENCES Location (Address),
FOREIGN KEY (Employee_EmployeeID_Passenger) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Drop) REFERENCES Location (Address));
You need to reference UNIQUE or PRIMARY KEY column:
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking VARCHAR(90) NOT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking, DateOfShift),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(Name), -- name is not UNIQUE/PK
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime)
);
to:
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeID INT NOT NULL, -- here
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeID, DateOfShift),
FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime)
);
SqlFiddleDemo

MySql error 1215: Cannot add foreign key constraint

in my RIM I got the 1215 MySql error.
I know the meaning of the error, that my constraints are wrong. But I can't seem to fix it.
the error is at line 33, the creation of table Poker_event
create table Poker_event
(date_time datetime not null,
min_players int not null,
max_players int not null,
house_number int not null,
postal_code varchar(6) not null,
primary key(date_time),
foreign key(house_number, postal_code) references Location(house_number, postal_code) on delete set null on update cascade);
my code is:
create database FullHouseGr1;
use FullHouseGr1;
create table Player
(player_id int not null,
first_name varchar(20) not null,
surname varchar(20) not null,
addres varchar(40) not null,
postal_code varchar(6) not null,
place varchar(40) not null,
phone_number varchar(20) not null,
email_addres varchar(255) not null,
points int not null,
primary key(player_id));
create table Location
(house_number int not null,
postal_code varchar(6) not null,
capacity int not null,
place varchar(40) not null,
street varchar(40) not null,
primary key(house_number, postal_code));
create table Poker_event
(date_time datetime not null,
min_players int not null,
max_players int not null,
house_number int not null,
postal_code varchar(6) not null,
primary key(date_time),
foreign key(house_number, postal_code) references Location(house_number, postal_code) on delete cascade on update cascade);
create table Tournament
(date_time datetime not null,
prize int not null,
primary key(date_time),
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade);
create table Tournament_round
(round_nr int not null,
date_time datetime not null,
primary key(date_time, round_nr),
foreign key(date_time) references Tournament(date_time) on delete no action on update cascade);
create table Tournament_table
(winner int not null,
date_time datetime not null,
round_nr int not null,
primary key(winner, date_time, round_nr),
foreign key(date_time) references Tournament(date_time) on delete no action on update cascade,
foreign key(round_nr) references Tournament(round_nr) on delete no action on update cascade);
create table Professional
(p_name varchar(40) not null,
primary key(name));
create table Masterclass
(date_time datetime not null,
min_rating int not null,
name varchar(40) not null,
primary key(date_time),
foreign key(p_name) references Professional(p_name) on delete no action on update cascade,
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade);
create table Poker_event_player
(date_time datetime not null,
has_payed boolean not null,
player_id int not null,
primary key(date_time, player_id),
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade,
foreign key(player_id) references Player on delete no action on update cascade);
create table Player_tournament_table
(winner int not null,
date_time datetime not null,
round_nr int not null,
player_id int not null,
primary key(winner, date_time, round_nr, player_id),
foreign key(winner) references Tournament_table on delete no action on update cascade,
foreign key(round_nr) references Tournament_round on delete no action on update cascade,
foreign key(date_time) references Tournament on delete no action on update cascade,
foreign key(player_id) references Player on delete no action on update cascade);
You're saying ON DELETE SET NULL but both of the fields in question are not nullable. Try ON DELETE CASCADE instead.
You can also check to make sure both tables are using the InnoDB engine.

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