ERROR 1005 (HY000) mySql, on small database [duplicate] - mysql

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.

Related

MySQL Cannot add Foreign Key Constraint MySQL

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

MySQL Database Creation, multiple foreign key errors?

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.

MySql Error 1005 erno:105 Can't create table

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.

Error 1215: Cannot add foreign key constraint - MySQL (Simple Tables)

The current tables I have are as follows:
CREATE TABLE course(
CourseNum INT(11),
CourseName VARCHAR(30),
NumOfUnit INT(11),
PRIMARY KEY(CourseNum)
);
CREATE TABLE timeandloc(
CourseNum INT(11),
Quarter VARCHAR(20),
DayTime VARCHAR(40),
RoomNum INT,
PRIMARY KEY(CourseNum, Quarter, DayTime),
FOREIGN KEY(CourseNum) REFERENCES course (CourseNum)
);
I was able to add those fine using a query, but when I try to add this table:
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
I get
Error code: 1215. Cannot add foreign key constraint.
It seems to be this line that's the culprit:
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
When I try to add the table without that line, everything works fine without a hitch.
I'm very new to MySQL and databases in general so I'm not sure what's wrong. Any help would be great. Thanks.
create a separate index on Quarter field in timeandloc table and then create problematic create table query.
alter table timeandloc add index idx_Quarter(Quarter);
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
Update:
For performance point of view joining field in both tables (parent/child) should be indexed. When we create foreign key then mysql itself create an index on the field we create foreign key but could not allow without index on referenced column in referenced table. As index works from left to right, so in your case index for Quarter column will not be used from primary key, so need to create a separate index on it.

MySQL, MariaDB: Cannot create a table - ERROR 1005 (HY000). Something wrong with foreign key

I am new to databases and I keep getting an error when I try to create these tables. Where is a mistake?
I have found loads of questions similar to mine, but they didn't help me to resolve this problem.
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);
This is from INNODB STATUS.
LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
FOREIGN KEY (course_name) REFERENCES course (course_name)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Your primary key is set to cou_id and course_name in your course table. To add a foreign key constraint in your students_marks table, you'd have to reference both fields (and include both fields in your table definition):
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
cou_id VARCHAR(3),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);
SQL Fiddle Demo
You are referencing only one field of a composed primary key!