drop table if exists patient;
drop table if exists pan;
drop table if exists device;
drop table if exists sensor;
drop table if exists actuator;
drop table if exists wears;
drop table if exists connects;
drop table if exists period;
drop table if exists reading;
drop table if exists setting;
drop table if exists lives;
drop table if exists municipality;
create table patient
(patient_name varchar(255),
patient_number integer(10),
patient_address varchar(255),
primary key(patient_number));
create table pan
(pan_domain varchar(255),
pan_phone integer(9),
primary key(pan_domain));
create table device
(device_snum integer(10),
device_manuf varchar(255),
device_description varchar(255),
primary key(device_snum, device_manuf));
create table municipality
(municipality_nut4code integer(10),
municipality_name varchar(255),
primary key(municipality_nut4code));
create table period
(period_start time,
period_end time,
primary key(period_start, period_end));
create table sensor
(sensor_snum integer(10),
sensor_manuf varchar(255),
sensor_units varchar(255),
primary key(sensor_snum, sensor_manuf),
foreign key(sensor_snum) references device(device_snum),
foreign key(sensor_manuf) references device(device_manuf));
create table actuator
(actuator_snum integer(10),
actuator_manuf varchar(255),
actuator_units varchar(255),
primary key(actuator_snum, actuator_manuf),
foreign key(actuator_snum) references device(device_snum),
foreign key(actuator_manuf) references device(device_manuf));
create table wears
(wears_start time,
wears_end time,
wears_patient integer(10),
wears_pan varchar(255),
primary key(wears_start, wears_end, wears_patient),
foreign key(wears_start) references period(period_start),
foreign key(wears_end) references period(period_end),
foreign key(wears_patient) references patient(patient_number),
foreign key(wears_pan) references pan(pan_domain));
create table connects
(connects_start time,
connects_end time,
connects_snum integer(10),
connects_manuf varchar(255),
connects_pan varchar(255),
primary key(connects_start, connects_end, connects_snum, connects_manuf),
foreign key(connects_start) references period(period_start),
foreign key(connects_end) references period(period_end),
foreign key(connects_snum) references device(device_snum),
foreign key(connects_manuf) references device(device_manuf),
foreign key(connects_pan) references pan(pan_domain));
create table reading
(reading_snum integer(10),
reading_manuf varchar(255),
reading_datetime date,
reading_value numeric(10,2),
primary key(reading_snum, reading_manuf, reading_datetime),
foreign key(reading_snum) references sensor(sensor_snum),
foreign key(reading_manuf) references sensor(sensor_manuf));
create table setting
(setting_snum integer(10),
setting_manuf varchar(255),
setting_datetime date,
setting_value numeric(10,2),
primary key(setting_snum, setting_manuf, setting_datetime),
foreign key(setting_snum) references actuator(actuator_snum),
foreign key(setting_manuf) references actuator(actuator_manuf));
create table lives
(lives_start time,
lives_end time,
lives_patient integer(10),
lives_municipality integer(10),
primary key(lives_start, lives_end, lives_patient),
foreign key(lives_start) references period(period_start),
foreign key(lives_end) references period(period_end),
foreign key(lives_patient) references patient(patient_number),
foreign key(lives_municipality) references municipality(municipality_nut4code));
When I try to create this database on MySQL I get an error saying ERROR 1005 (HY000) can't create table ***** (errno: 150). The tables that can't be created are the ones which have foreign keys. I already checked the data types and that the references match a primary key of a previously created table.
I don't get the error. Can someone help?
Since you have composite keys in the tables you're referencing, you should make the foreign key composite as well. For example:
create table sensor
(sensor_snum integer(10),
sensor_manuf varchar(255),
sensor_units varchar(255),
primary key(sensor_snum, sensor_manuf),
foreign key(sensor_snum, sensor_manuf) references device(device_snum, device_manuf));
Also, if you have two tables with the same foreign key, you need to give names to the foreign keys. All foreign keys need to have different names, and if you don't give a name explicitly, MySQL generates the name based just on the columns in the foreign key, and you'll end up with duplicates.
Related
I am having a hard time understanding why my code is giving me cannot add foreign key constraint error. I just started coding in MySQL so I am sorry for anything dumb.
drop table if exists COURSE_INSTRUCTORJG;
drop table if exists CLASSJG;
drop table if exists COURSEJG;
drop table if exists INSTRUCTORJG;
create table INSTRUCTORJG(
InstructorID int,
DepartHead int,
primary key(InstructorID)
);
create table COURSEJG(
CourseNo char(10),
ComputerNeeded smallint,
primary key(CourseNo)
);
create table CLASSJG(
Building CHAR(20),
RoomNum smallint,
Maxcap int,
primary key(Building, RoomNum)
);
create table COURSE_INSTRUCTORJG (
COURSEJG_CourseNo CHAR(10),
INSTRUCTORJG_InstructorID INT,
Semester CHAR(20),
Section INT,
CLASSJG_Building char(20),
CLASSJG_RoomNum smallint,
primary key(COURSEJG_CourseNo, INSTRUCTORJG_InstructorID, Semester, Section),
foreign key (COURSEJG_CourseNo) references COURSEJG(CourseNo),
foreign key (INSTRUCTORJG_InstructorID) references INSTRUCTORJG(InstructorID),
foreign key (CLASSJG_Building) references CLASSJG(Building),
foreign key (CLASSJG_RoomNum) references CLASSJG(RoomNum)
);
My error is coming from the line: foreign key (CLASSJG_RoomNum) references CLASSJG(RoomNum).
You can reference primary key, keys or unique comnstrqaint, but in table CLASSJG you have a double primary key, so reference both columns or define another key
create table CLASSJG(
Building CHAR(20),
RoomNum smallint,
Maxcap int,
primary key(Building, RoomNum),
KEY(RoomNum)
);
see sample fiddle
This question already has an answer here:
ERRO 1215. MySql InnoDB
(1 answer)
Closed 2 years ago.
Hey so i just started using mysql and made a small database, but then i tried to alter some tables to impliment some foreign keys and I got the error: ERROR 1005 (HY000): Can't create table etron3.purchase (errno: 150 "Foreign key constraint is incorrectly formed").
I know its cause when altering TillNo into a foreing key of TillN, but i cant really see what the problem is.
create table BRANCH(BranchNo INT, BranchAddr VARCHAR(25), BranchTell INT, PRIMARY KEY(BranchNo));
/*Create table CUSTOMER*/
create table CUSTOMER(CustNum INT, CustTell INT, CustFname VARCHAR(15), CustLname VARCHAR(15), CustCountry VARCHAR(20),
CustTown VARCHAR(20), CustStreet VARCHAR(20), CustPostCode CHAR(7), CustDob DATE, CustEmail VARCHAR(45), PRIMARY KEY(CustNum, CustTell));
/*Create table ASSISTANT*/
create table ASSISTANT(SalesPNo INT,TillN INT , SalePFname VARCHAR(20), SalePLname VARCHAR(20), PRIMARY KEY(SalesPNo, TillN));
/*Create table PURCHASE*/
create table PURCHASE(TDateTime DATETIME, TillNo INT, CustNo INT, AssistantNo INT, ProdCode INT, Qty INT, PRIMARY KEY(TDateTime));
/*Create table SUPPLIER*/
create table SUPPLIER(SupCnum INT, SupCname VARCHAR(15), SupFname VARCHAR(15), SupLname VARCHAR(15), SupEmail VARCHAR(30), ProdNum INT, PRIMARY KEY(SupCnum));
/*Create table PRODUCT*/
create table PRODUCT(ProductCode INT, PType VARCHAR(20), Price INT, OfferPrice INT, PRIMARY KEY(ProductCode, PType));
/*Create table PRODTYPE*/
create table PRODTYPE(ProdGroup VARCHAR(20), PCode INT, PRIMARY KEY(ProdGroup));
/*Altering tables, adding foreign keys, so that I don't get any errors*/
/*Add primary and foreign keys to PURCHASE*/
ALTER TABLE PURCHASE
ADD FOREIGN KEY(AssistantNo) REFERENCES ASSISTANT(SalesPNo);
ALTER TABLE PURCHASE
ADD FOREIGN KEY(ProdCode) REFERENCES PRODUCT(ProductCode);
ALTER TABLE PURCHASE
ADD FOREIGN KEY(CustNo) REFERENCES CUSTOMER(CustNum);
ALTER TABLE PURCHASE
ADD FOREIGN KEY (TillNo) REFERENCES ASSISTANT(TillN);
/*Add foreign key to SUPPLIER*/
ALTER TABLE SUPPLIER
ADD FOREIGN KEY(ProdNum) REFERENCES PRODUCT (ProductCode);
/*Add primary and foreign keys to PRODTYPE*/
ALTER TABLE PRODTYPE
ADD FOREIGN KEY(PCode) REFERENCES PRODUCT(ProductCode);
Consider this part of your code:
ALTER TABLE PURCHASE
ADD FOREIGN KEY(AssistantNo) REFERENCES ASSISTANT(SalesPNo);
ALTER TABLE PURCHASE
ADD FOREIGN KEY (TillNo) REFERENCES ASSISTANT(TillN);
The primary key of the ASSISTANT table is (SalesPNo, TillN).
Technically, you cannot have a foreign key point at the second column only of the other table's primary key - MySQL wants the referred column to be indexed, or to appear first in a compound index.
Functionnaly, you most probably want a compound foreign key rather than two individual foreign keys, so:
ALTER TABLE PURCHASE
ADD FOREIGN KEY (AssistantNo, TillNo) REFERENCES ASSISTANT(SalesPNo, TillN);
With this change, your script runs succesfully in this db fiddle.
Recommended reading: MySQL Foreign Keys - Constraints and Restrictions.
So I'm trying to create a database in mySQL. I have a bunch of create table statements and a bunch of alter table statements. However, about half of the alter table statements are randomly giving me the 1215 "cannot add foreign key constraint" error, which is about as useful as a doctor telling me I have a broken bone and not telling me which one. Anyways, here is one of the ones that fails:
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID);
And here are the relevant create statements for that specific one. I made sure to specify that the columns are primary keys.
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader VARCHAR(50), Employee_assistant VARCHAR(50),PRIMARY KEY(Instance_ID, Trip_ID));
CREATE TABLE Signups (Customer_ID INT, Trip_ID INT, Insurance_Form BOOLEAN, PRIMARY KEY (Customer_ID, Insurance_Form, Trip_ID));
EDIT:
So I used:
set foreign_key_checks=0;
Without really knowing what it does, and instead of error code 1215, I now get a bunch of 1822/1825 error codes about indexes, but even when I add index statements to the create table statements, it fails telling me the same issue.
I'm just going to put all my statements below, maybe there is some big thing I'm missing:
CREATE DATABASE OAG_Club;
USE OAG_Club;
CREATE TABLE Customer (customer_ID INT, Name VARCHAR(50), Home_Phone VARCHAR(10), Work_Phone VARCHAR(10), DOB DATE, Address VARCHAR(50), Customer_Type VARCHAR(50), Sponsor_ID INT, PRIMARY KEY(customer_ID));
CREATE TABLE Signups (Customer_ID INT, Trip_ID INT, Insurance_Form BOOLEAN, PRIMARY KEY (Customer_ID, Insurance_Form, Trip_ID));
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader VARCHAR(50), Employee_assistant VARCHAR(50),PRIMARY KEY(Instance_ID, Trip_ID));
CREATE TABLE Trip_Type (Trip_ID INT, Trip_Name VARCHAR(50), DIFF_lvl INT, Trip_Fee INT, Trip_Length INT, PRIMARY KEY (Trip_ID));
CREATE TABLE Rental_Agreement (Agreement_Number INT, Start_Date DATE, customer_ID INT, employee_ID INT, PRIMARY KEY (Agreement_Number));
CREATE TABLE Rental_Detail (Expected_Return DATE, Real_Return DATE, item_number INT, agreement_num INT);
CREATE TABLE Inventory (Item_Number INT, `Condition` VARCHAR(50), equip_name VARCHAR(50), PRIMARY KEY (Item_Number));
CREATE TABLE Equipment (Equip_Name VARCHAR(50), Student_Fee FLOAT, FacStaffAl_Fee FLOAT, Guest_Fee FLOAT, PRIMARY KEY (Equip_Name));
CREATE TABLE OAG_Employee (Employee_ID INT, Employee_Name VARCHAR(50), Start_Date DATE, End_Date DATE, Position_ID INT, PRIMARY KEY (Employee_ID));
CREATE TABLE Position (Position_ID INT, Position_Descr VARCHAR(50), Position_Salary FLOAT, PRIMARY KEY (Position_ID));
set foreign_key_checks=0;
ALTER TABLE inventory ADD FOREIGN KEY (equip_name) REFERENCES equipment(equip_name);
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(sponsor_ID);*/Nope*/
ALTER TABLE signups ADD FOREIGN KEY (customer_ID) REFERENCES customer(customer_ID);
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Instance(Trip_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE rental_agreement ADD FOREIGN KEY (customer_id) REFERENCES customer(customer_id);
ALTER TABLE rental_agreement ADD FOREIGN KEY (employee_id) REFERENCES oag_employee(employee_id);
ALTER TABLE rental_detail ADD FOREIGN KEY (item_number) REFERENCES inventory(item_number);
ALTER TABLE rental_detail ADD FOREIGN KEY (agreement_num) REFERENCES rental_agreement(agreement_num); /*nope*/
ALTER TABLE oag_employee ADD FOREIGN KEY (position_ID) REFERENCES `position`(position_ID);`
A foreign key in a table has to point to a primary key in another table, not just part of the primary key. So in your table Signups, the primary key is a composite PK consisting of three columns. The foreign key in another table must have the equivalent three columns included. Generally I think it is better to set a single column PK, then it is easier to define single column FKs in other tables. By all means set a Unique constraint on the three columns if you need that, but have a separate identity column as the PK.
So for the ones it's complaining about:
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(sponsor_ID);
*/Nope - FK column is not referencing a PK column. PK column in customer is customer_ID. Is this a self-referencing table? If so then...*/
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(customer_ID);
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Instance(Trip_ID);
/*nope - Trip_ID is the PK in table Trip_Type, not Trip_Instance, so...*/
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Type(Trip_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID);
/*nope - same as above, so...*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Type(Trip_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader) REFERENCES OAG_Employee(Employee_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant) REFERENCES OAG_Employee(Employee_ID);
/*nope - for both of these the FK column is varchar(50) but the referenced column is INT. What you should have is...*/
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader_ID INT, Employee_assistant_ID INT,PRIMARY KEY(Instance_ID, Trip_ID));
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader_ID) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant_ID) REFERENCES OAG_Employee(Employee_ID);
Hope this helps.
I am creating a WebApp for my stage tech crew to proper manage our hours worked. When I try to create a table 'Worked' I get a foreign key constraint error.
USE MySLS;
DROP TABLE IF EXISTS People;
DROP TABLE IF EXISTS Events;
DROP TABLE IF EXISTS Worked;
CREATE TABLE People
(pid int PRIMARY KEY,
pname varchar(255)
);
CREATE TABLE Events
(eid int PRIMARY KEY,
ename varchar(255),
edate DATE
);
CREATE TABLE Worked
(
pid int,
eid int,
hours decimal(3,1),
FOREIGN KEY (pid) REFERENCES People,
FOREIGN KEY (eid) REFERENCES Events
);
Data types are the same, I see no reason why this shouldn't work. Any thoughts?
shouldn't it go like this :
FOREIGN KEY(pid) REFERENCES People(pid)
FOREIGN KEY (eid) REFERENCES Events(eid)
I cannot create the table Item_Copy
CREATE TABLE Library
(
Library_ID int primary key,
Library_Address varchar(40),
Library_Phone bigint
);
CREATE TABLE Branch
(
Library_ID int,
Branch_Number int,
Branch_Name varchar(40),
Branch_Address varchar(40),
Branch_Phone bigint,
Branch_Hours varchar(40),
primary key (Library_ID,Branch_Number),
foreign key (Library_ID) references Library(Library_ID)
);
CREATE TABLE Item_Copy
(
Item_ID int primary key,
Copy_Number int,
Copy_Condition varchar(40),
Copy_Date_Acquired date,
Copy_Cost int,
Library_ID int,
Branch_Number int,
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
foreign key (Item_ID) references Item(Item_ID)
);
Just a scientific guess (will drop if it's wrong) (is based on an assumption that Item_ID definitions match):
You wanted a compound foreign key, not 2 separated FKs:
foreign key (Library_ID, Branch_Number) references Branch(Library_ID, Branch_Number)
To define a child relation, parent column must have indexed.
In the parent table Branch, Key is defined as composite.
primary key (Library_ID,Branch_Number),
But, in the child table Item_Copy, you are trying to define reference keys independent on each column.
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
This is only acceptable when each of these fields are referring to respective parent keys.
But Branch(Branch_Number) has no key defined in Branch table. And hence is the error.
Change:
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
To:
foreign key (Library_ID, Branch_Number)
references Branch(Library_ID, Branch_Number),