MySQL error #1064 - mysql

Hi all I can't find the error in this table creation bit, seems really straight forward to be, here's what it's giving me:
ERROR 1064 at line 3: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'FOREIGN KEY(courses_courseDepartmentAbbv))' at
line 8
DROP TABLE IF EXISTS courses;
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher),
FOREIGN KEY (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv),
FOREIGN KEY (departments_departmentAbbv) REFERENCES (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName),
FOREIGN KEY (teachers_teacherName) REFERENCES (courses_courseTeacher)
);

You need to have a References after each Foreign key. You are missing that in the beginning setup of courses. Here is the documentation
I think this is more of what you want. Your order of creation was not correct. You had foreign keys in the wrong location due to this. You only set up foreign key mappings on the tables with the relations to the PK. You only need to set up the PK on your other tables. As long as you create the tables in the right order, then you can do this, as below.
So, teachers and departments have primary keys that are foreign keys within the courses table. teachers and departments does not need to worry about the foreign key. You leave that up to the table that actually has the reference (courses)
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName)
--FOREIGN KEY (teachers_teacherName) REFERENCES courses (courses_courseTeacher)
--This is not where you set up the FK for courses
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv)
--FOREIGN KEY (departments_departmentAbbv) REFERENCES courses (courses_courseDepartmentAbbv)
--This is not where you set up the FK for courses
);
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher)
REFERENCES teachers (teachers_teacherName)
FOREIGN KEY (courses_courseDepartmentAbbv)
REFERENCES departments(departments_departmentAbbv)
);

You need to give a REFERENCES clause for your FOREIGN KEY clauses
FOREIGN KEY (courses_courseTeacher)
FOREIGN KEY (courses_courseDepartmentAbbv)

Define engine type that should be innodb which supports FOREIGN KEY constraints.
Follow Syntax defined here

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

Unable to create foreign key reference with different column lables

While I am creating schema "Cannot add foreign key constraint" error I am getting.
Query is :
CREATE database sample;
USE sample;
CREATE TABLE sys_admin_user_t (
sys_admin_id MEDIUMINT NOT NULL,
admin_name VARCHAR(255) NOT NULL,
admin_password VARCHAR(255) NOT NULL,
PRIMARY KEY (sys_admin_id)
);
CREATE TABLE sys_user_roles_t (
role_id MEDIUMINT NOT NULL,
privilege_id MEDIUMINT NOT NULL,
role_name VARCHAR(255) NOT NULL,
role_description VARCHAR(255) NOT NULL,
created_by MEDIUMINT NOT NULL,
created_date DATE NOT NULL,
modified_by MEDIUMINT NOT NULL,
FOREIGN KEY (privilege_id) REFERENCES privileges_t (privilege_id),
FOREIGN KEY (created_by) REFERENCES sys_admin_user_t(sys_admin_id),
FOREIGN KEY (modified_by) REFERENCES sys_admin_user_t(sys_admin_id),
PRIMARY KEY (role_id)
);
Kindly some one help me to resolve this.
This can occur in the following cases:
You do not create the table privileges_t
In your table privileges_t does not exists primary key by field privilege_id
The field privilege_id from table sys_user_roles_t are not exactly the same data type as in table privileges_t
You are not using InnoDB as the engine on all tables
And to find the specific error run this:
SHOW ENGINE INNODB STATUS\G

#1005 - Can't create table on ALTER TABLE when connecting table via FOREIGN KEY

I am working on a homework assignment. I have to build a database for a video store. All of the following works:
CREATE TABLE Stock
(
PKStock_ID VARCHAR(8) NOT NULL,
FKTitle VARCHAR(8) NOT NULL,
NoOfDVD INT(10) NOT NULL,
NoOfVHS INT(10) NOT NULL,
PRIMARY KEY (PKStock_ID)
);
CREATE TABLE Inventory
(
PKUnique_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Distributor_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
InStock CHAR(1) NOT NULL,
DateOut TIMESTAMP,
DateBack TIMESTAMP,
Customer_ID VARCHAR(8) NOT NULL,
Rental_Price DECIMAL(4,2) NOT NULL,
PRIMARY KEY (PKUnique_ID)
);
CREATE TABLE Movie
(
PKTitle_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
Title VARCHAR(30),
Genre VARCHAR(8),
YearReleased INT,
Length INT,
PRIMARY KEY (PKTitle_ID)
);
CREATE TABLE Actors
(
PKActor_ID VARCHAR(8) NOT NULL,
FKActor_ID VARCHAR(8) NOT NULL,
Actors VARCHAR(30),
PRIMARY KEY (PKActor_ID)
);
CREATE TABLE Awards
(
PKAward_ID VARCHAR(8) NOT NULL,
FKAward_ID VARCHAR(8) NOT NULL,
Awards VARCHAR(30),
PRIMARY KEY (PKAward_ID)
);
CREATE TABLE Directors
(
PKDirector_ID VARCHAR(8) NOT NULL,
FKDirector_ID VARCHAR(8) NOT NULL,
Directors VARCHAR(30),
PRIMARY KEY (PKDirector_ID)
);
CREATE TABLE ElectronicCatalogue
(
PKElectronicCatalogue VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (PKElectronicCatalogue)
);
CREATE TABLE Distributors
(
PKDistributor_ID VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
NameOfDistributer VARCHAR(30) NOT NULL,
Horror CHAR(1) NOT NULL,
Drama CHAR(1) NOT NULL,
Comedy CHAR(1) NOT NULL,
Action CHAR(1) NOT NULL,
Thrillers CHAR(1) NOT NULL,
PRIMARY KEY (PKDistributor_ID)
);
CREATE TABLE Customers
(
PKCustomer_ID VARCHAR(8) NOT NULL,
FKUnique_ID VARCHAR(8) NOT NULL,
Name VARCHAR(30),
Address VARCHAR(100),
Phone INT NOT NULL,
PRIMARY KEY (PKCustomer_ID)
);
CREATE TABLE Fees
(
PKFee_ID VARCHAR(8) NOT NULL,
FK_ID VARCHAR(8) NOT NULL,
Damages DECIMAL(10,2) NOT NULL,
Late DECIMAL(10,2) NOT NULL,
PRIMARY KEY (PKFee_ID)
);
ALTER TABLE Stock
ADD FOREIGN KEY (FKTitle)
REFERENCES Inventory(PKUnique_ID);
ALTER TABLE Movie
ADD FOREIGN KEY (FKTitle_ID)
REFERENCES Stock (PKStock_ID);
ALTER TABLE Actors
ADD FOREIGN KEY (FKActor_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Awards
ADD FOREIGN KEY (FKAward_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Directors
ADD FOREIGN KEY (FKDirector_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE ElectronicCatalogue
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES Inventory (PKUnique_ID);
ALTER TABLE Distributors
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES ElectronicCatalogue (PKElectronicCatalogue);
I next want to connect the Inventory table to the customers table. When I do the following:
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
I get this error:
#1005 - Can't create table 'mm.#sql-9f69_110' (errno: 150)
What am I doing wrong?
Foreign key should point to a unique column (primary key or unique). Your Inventory (Customer_ID) is not unique.
I think you are trying to :
ALTER TABLE Inventory
ADD CONSTRAINT fk1_Inv FOREIGN KEY (Customer_ID)
REFERENCES Customers (PKCustomer_ID);
Not sure why you didn't get the full message but there's a command line tool bundled with MySQL that provides further information about cryptic error messages like this (or you can just Google for the error code):
C:>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
If you have the SUPER privilege, you can get further details with this query:
show engine innodb status
And in this case you see this:
LATEST FOREIGN KEY ERROR
------------------------
130226 21:00:25 Error in foreign key constraint of table test/#sql-1d98_1:
FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID):
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.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So you are missing an index as explained.
Edit: As other answers point out, if there's no index it's because you're linking to the wrong column.
As Álvaro G. Vicario says you are missing an index, this is because you are not correctly using foreign keys.
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
This should be:
ALTER TABLE Inventory
ADD FOREIGN KEY (Customer_ID)
REFERENCES Customer(PKCustomer_ID);
The foreign key checks if the customer in the Inventory table actually exists in the Customers table. Thus Inventory here is the table you want to add the foreign key too and it references in primary key in the Customer table.
What you are trying to do is reference the Customer_ID in Inventory, which is just an VARCHAR(8)column and not an Primary Key (Index).
You should double check your other alter statements as well.
This turns out that you have different collation settings between these tables. In my case we had latin_swedish_ci and utf8_general_ci

MySQL creating a table (errno 150)

I would like to ask something that troubles me many many days...
Here is what I mean:
I create these two tables:
CREATE TABLE IF NOT EXISTS journal (
issn varchar(20) NOT NULL,
j_title varchar(100) NOT NULL,
j_publisher varchar(30) NOT NULL,
PRIMARY KEY (issn)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS volume (
volume_no int(11) NOT NULL,
issn varchar(20) NOT NULL,
year int(11) NOT NULL,
PRIMARY KEY (issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn)
) ENGINE=InnoDB;
When I try to create this:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn),
FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
) ENGINE=InnoDB;
it throws an error (errno 150)
The error is in the foreign key volume_no.
Without FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
the table is created without a problem.... I can't explain what's going on... I have seen it many times again and again but nothing!! Does anybody know what's going on?
Thanks in advance!!
I could see that the foreign key doesnt include issn but which is actually included in primary key for volumn table.
CREATE TABLE IF NOT EXISTS issue ( issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn,volume_no) REFERENCES volume(issn,volume_no) ) ENGINE=InnoDB;
Look at the below sql fiddle.
http://sqlfiddle.com/#!2/55a63
maybe volume_no needs to be UNSIGNED
FOREIGN keys must reference a PRIMARY or a UNIQUE key in the parent table.
You need only one Foreign Key at table issue, not two. And it should reference the Primary Key of volume:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issn, volume_no, issue_no),
FOREIGN KEY (issn, volume_no)
REFERENCES volume(issn, volume_no)
) ENGINE=InnoDB;
If the PK of the parent table is more than one field, the order of the fields in the FK must be the same as the order in the PK.
issue: FOREIGN KEY (issn, volume_no) REFERENCES volume(issn, volume_no)
These conditions must be satisfied to not get error 150:
The two tables must be ENGINE=InnoDB.
The two tables must have the same charset.
The PK column(s) in the parent table and the FK column(s) must be the same data type.
The PK column(s) in the parent table and the FK column(s), if they have a define collation type, must have the same collation type;
If there is data already in the foreign key table, the FK column value(s) must match values in the parent table PK columns.
source: MySQL Creating tables with Foreign Keys giving errno: 150
I had about the same issue with my database. It wasn't about the definition of the foreign key, actually it was the definition of the primary key field.
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNIQUE NOT NULL AUTO_INCREMENT ,
CREATE TABLE tblProcessesMessage (
fldProcesses TEXT NOT NULL,
fldProcessesID VARCHAR(15) NOT NULL DEFAULT ,
The primary key in tblProcesses (fldProcessesID) did not have the UNSIGNED keyword while the foreign key in tblProcessesMessage (fldProcessesID) had the UNSIGNED keyword. This keyword was causing the problem - inconsistent type of field. So i added the UNSIGNED keyword to fldProcessesID in tblPreocesses:
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNSIGNED UNIQUE NOT NULL AUTO_INCREMENT,
I hope that this will help you solve your problems.
Best regards,
Nicholas

mysql innoDB error 1005

I'm trying to find what causes error 1005 on creation of my tables:
CREATE TABLE hospitals(
hosp_id INT NOT NULL AUTO_INCREMENT,
hosp_name VARCHAR(100) NOT NULL,
hosp_address VARCHAR(100) NOT NULL,
hosp_ph_number VARCHAR(8) NOT NULL,
PRIMARY KEY(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE transport(
tr_regnumber VARCHAR(8) NOT NULL,
tr_brand VARCHAR(15) NOT NULL,
tr_description VARCHAR(25),
hosp_id INT,
PRIMARY KEY (tr_regnumber),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE buildings(
build_id INT NOT NULL AUTO_INCREMENT,
hosp_id INT,
build_address VARCHAR(100) NOT NULL,
build_description VARCHAR(25),
PRIMARY KEY (build_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE patients(
pat_id INT NOT NULL AUTO_INCREMENT,
pat_fullname VARCHAR(150) NOT NULL,
diagnosis VARCHAR(150) NOT NULL,
emp_id INT,
pat_ph_number VARCHAR(8),
pat_address VARCHAR(100),
hosp_id INT,
pl_num INT,
PRIMARY KEY (pat_id),
FOREIGN KEY (pl_num) REFERENCES places(pl_number),
FOREIGN KEY (emp_id) REFERENCES employees(emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE places(
pl_number INT NOT NULL AUTO_INCREMENT,
pat_id INT NOT NULL,
hosp_id INT NOT NULL,
PRIMARY KEY (pl_number),
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE employees(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_fullname VARCHAR(150) NOT NULL,
emp_position VARCHAR(100) NOT NULL,
emp_ph_number VARCHAR(8),
emp_home_address VARCHAR(100),
hosp_id INT NOT NULL,
PRIMARY KEY (emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
Here are errors:
ERROR 1005 (HY000): Can't create table 'hospital_db.patients' (errno: 150)
ERROR 1005 (HY000): Can't create table 'hospital_db.places' (errno: 150)
Here's output of SHOW INNODB STATUS:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110829 11:52:01 Error in foreign key constraint of table hospital_db/places:
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8:
Cannot resolve table name close to:
(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8
I use MySQL v5.1.49.
This seems to be to do with the order you're creating the tables and the foreign key dependencies you have.
Try disabling foreign key checks before creating the tables and enabling them after like so:
SET foreign_key_checks = 0;
-- Your create queries here
SET foreign_key_checks = 1;
Cheers
I know this one is solved, but for the Googlers out here, I did this in mysql workbench:
Primary keys have 'not null' checked by default. Creating a foreign key in a child table and also checking it as 'not null' will cause this error. It took me ages to find this myself because its an exception of what people suggest (making sure everything in the column is of the same type as the parent key). So just leave 'not null' unchecked on the foreign key
thought this might help saving people some time :)
You create FK on table 'places' before creating this table. Table places is created after table patients which try to use table which doesn't exist yet.
It seems that you have crossing foreign keys. In this case it's better to create tables without FKs and than use ALter TABLE for adding FKs.