I'm creating a MySQL database for homework, and running into syntax error #1005 in phpmyadmin. I think it has something to do with the foreign keys but if w3schools has is right my syntax should be good.
Here's the SQL statements;
create table if not exists customers
(
id int not null auto_increment,
cust_gname varchar(20) not null,
cust_fname varchar(30) not null,
cust_street varchar(30) not null,
cust_suburb varchar(30) not null,
cust_state varchar(6) not null,
cust_postcode varchar(4) not null,
cust_email varchar(50) not null,
cust_phone varchar(12),
cust_mobile varchar(12),
cust_user_id int,
foreign key (cust_user_id) references users(id),
primary key (id)
);
create table if not exists ingredients
(
id int,
name varchar(30) not null,
primary key (id)
);
create table if not exists recipes
(
id int,
name varchar(30) not null,
recipes_menu_id int,
foreign key (recipes_menu_id) references menus(id)
image varchar(30),
primary key (id)
);
create table if not exists ingredients_recipes
(
id int,
ingredients_recipes_ingredient_id int,
foreign key (ingredients_recipes_ingredient_id) references ingredients(id),
ingredients_recipes_recipe_id int,
foreign key (ingredients_recipes_recipe_id) references recipes(id),
primary key (id)
);
create table if not exists menus
(
id int,
description varchar(30) not null,
menus_restaurant_id int,
foreign key (menus_restaurant_id) references restaurants(id),
primary key (id)
);
create table if not exists restaurants
(
id int,
name varchar(30) not null,
address1 varchar(30) not null,
address 2 varchar(30),
suburb varchar(30) not null,
state varchar(10) not null,
postcode varchar(4) not null,
primary key (id)
);
create table if not exists customers_ingredients
(
id int,
customers_ingredients_customer_id int,
foreign key (customers_ingredients_customer_id) references customers(id),
customers_ingredients_ingredient_id int,
foreign key (customers_ingredients_ingredient_id) references ingredients(id),
primary key (id)
);
create table if not exists users
(
id int,
username varchar(40) not null,
password varchar(50) not null,
group_id int,
created DATETIME,
modified DATETIME,
primary key (id)
);
create table if not exists groups
(
id int,
name varchar(10) not null,
created DATETIME,
modified DATETIME,
primary key (id)
);
If you're creating a table with a foreign key reference, the table to which it refers must already exist. You're creating a customers table at the start of the script which refers to the users table which isn't created until near the end. There are other examples in the script too.
You need either to create the tables in the right order, or use set foreign_key_checks = 0; at the top to disable this requirement. Make sure you set foreign_key_checks = 1 at the end once all your tables are created.
Note: there may be other syntax errors in your script - I haven't checked it all.
Related
I'm trying to define some tables with SQL, but when I execute it I have an error. Below there is my code and the error which I receive.
CREATE TABLE Artists
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
description VARCHAR(255)
);
CREATE TABLE Albums
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
releasedate DATE,
artistid INT,
genreid INT,
picture VARCHAR(255),
CONSTRAINT `fk_albums_artists`
FOREIGN KEY (artistid) REFERENCES Artists(id),
CONSTRAINT `fk_albums_genres`
FOREIGN KEY (genreid) REFERENCES Genres(id)
);
CREATE TABLE Tracks
(
id INT(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
playtime INT NOT NULL,
albumid INT,
CONSTRAINT `fk_tracks_album`
FOREIGN KEY (albumid) REFERENCES Albums(id)
);
CREATE table Genres
(
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL
);
Error in my SQL query:
MySQL said: Documentation
1005 - Can't create table musicplayer.Albums (errno: 150 "Foreign
key
constraint is incorrectly formed") (Details…)
Declare the tables in order, so the tables are defined before they are referenced:
CREATE TABLE Artists (
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
description varchar(255)
);
CREATE table Genres(
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null
);
CREATE TABLE Albums (
id int AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
releasedate date,
artistid int,
genreid int,
picture varchar(255),
CONSTRAINT `fk_albums_artists` FOREIGN KEY (artistid) REFERENCES Artists(id),
CONSTRAINT `fk_albums_genres` FOREIGN KEY (genreid) REFERENCES Genres(id)
);
CREATE TABLE Tracks(
id int(11) AUTO_INCREMENT PRIMARY KEY NOT null,
name varchar(255) not null,
playtime int not null,
albumid int,
CONSTRAINT `fk_tracks_album` FOREIGN KEY (albumid) REFERENCES Albums(id)
);
Here is a db<>fiddle.
You can still have tables that reference each other. However, you will need to declare such foreign key constraints using ALTER TABLE rather than in the CREATE TABLE statement. However, you do not need to do this for these table definitions.
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
I'm working on building a small database and am running into a syntax error on these two lines in my last table.
They're foreign keys and those lines didn't produce any errors in the tables where they originally appeared.
INVOICE_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
DONUT_ID VARCHAR(10) NOT NULL UNIQUE,
These two lines are the PK and FK in the table, and I think this is where I'm running into the problem because I used the same syntax as I did in earlier tables that aren't generating any errors.
Here is the full code for four tables:
CREATE TABLE CUSTOMER (
CUST_ID INT NOT NULL AUTO_INCREMENT UNIQUE,
CUST_LNAME VARCHAR(25) NOT NULL,
CUST_FNAME VARCHAR(25) NOT NULL,
CUST_INITIAL CHAR(1),
CUST_STREET_NO VARCHAR(6),
CUST_STREET_NAME VARCHAR(25),
CUST_APT_NO VARCHAR(10),
CUST_CITY VARCHAR(25),
CUST_STATE CHAR(2),
CUST_ZIP_CODE CHAR(5),
CUST_HOME_AC CHAR(3),
CUST_HOME_PHONE CHAR(8),
PRIMARY KEY (CUST_ID)
)ENGINE = InnoDB;
CREATE TABLE INVOICE (
INVOICE_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
CUST_ID INTEGER NOT NULL,
INV_DATE DATE NOT NULL,
SPECIAL_HANDLING VARCHAR(35),
PRIMARY KEY (INVOICE_ID),
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(CUST_ID) ON UPDATE CASCADE
)ENGINE = InnoDB;
CREATE TABLE PRODUCT (
DONUT_ID VARCHAR(10) NOT NULL UNIQUE,
DONUT_NAME VARCHAR(25) NOT NULL,
DONUT_DESC VARCHAR(35) NOT NULL,
DONUT_PRICE DECIMAL(13,2) NOT NULL,
PRIMARY KEY (DONUT_ID)
)ENGINE = InnoDB;
CREATE TABLE INVOICE LINE ITEM (
INVOICE_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
DONUT_ID VARCHAR(10) NOT NULL UNIQUE,
DONUT_QTY INTEGER NOT NULL,
PRIMARY KEY (INVOICE_ID, DONUT_ID),
FOREIGN KEY (INVOICE_ID) REFERENCES INVOICE(INVOICE_ID) ON UPDATE CASCADE,
FOREIGN KEY (DONUT_ID) REFERENCES PRODUCT(DONUT_ID) ON UPDATE CASCADE
)ENGINE = InnoDB;
The fourth CREATE TABLE statement will fail because of the spaces in the table name:
CREATE TABLE INVOICE LINE ITEM ...
You should use a different name, without spaces. For example you could replace the spaces with underscores and use snake-case:
CREATE TABLE INVOICE_LINE_ITEM ...
This question already has an answer here:
MySQL Error 1005?
(1 answer)
Closed 7 years ago.
I'm getting this error, and I know it's coming from the DROP TABLE IF statements, but I don't know how else to organize the drops for it to work. I've tried rearranging them but it won't work. The problem came when I introduced the Passenger table but I don't know how to fix it.
DROP TABLE IF EXISTS `Passenger`;
DROP TABLE IF EXISTS `ProductInvoice`;
DROP TABLE IF EXISTS `Invoice`;
DROP TABLE IF EXISTS `Product`;
DROP TABLE IF EXISTS `Customer`;
DROP TABLE IF EXISTS `Person`;
DROP TABLE IF EXISTS `Airport`;
DROP TABLE IF EXISTS `Address`;
DROP TABLE IF EXISTS `Email`;
CREATE TABLE Address
(
AddressID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AddressID),
AddressStreet VARCHAR(255),
AddressCity VARCHAR(255),
AddressState VARCHAR(255),
AddressZip VARCHAR(255),
AddressCountry VARCHAR(255)
);
CREATE TABLE Email
(
EmailID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(EmailID),
EmailAddress VARCHAR(255)
);
CREATE TABLE Person
(
PersonID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PersonID),
PersonCode VARCHAR(255),
PersonLastName VARCHAR(255),
PersonFirstName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Address` (AddressID) REFERENCES Address(AddressID),
PersonPhone VARCHAR(255),
EmailID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Email` (EmailID) REFERENCES Email(EmailID)
);
CREATE TABLE Airport
(
AirportID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AirportID),
AirportCode VARCHAR(255),
AirportName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Airport_to_Address` (AddressID) REFERENCES Address(AddressID),
AirportLatDeg INT NOT NULL,
AirportLatMin INT NOT NULL,
AirportLongDeg INT NOT NULL,
AirportLongMin INT NOT NULL,
AirportPassFacilityFee FLOAT NOT NULL
);
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact INT NOT NULL,
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
CREATE TABLE Product
(
ProductID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductID),
ProductCode VARCHAR(255),
ProductType VARCHAR(255),
DepAirportCode INT,
FOREIGN KEY `fk_Product_to_Airport` (DepAirportCode) REFERENCES Airport(AirportID),
ArrAirportCode INT,
FOREIGN KEY `frk_Product_to_Airport` (ArrAirportCode) REFERENCES Airport(AirportID),
DepartureTime VARCHAR(255),
ArrivalTime VARCHAR(255),
FlightNumber VARCHAR(255),
FlightClass VARCHAR(255),
AircraftType VARCHAR(255),
SeasonStartDate VARCHAR(255),
SeasonEndDate VARCHAR(255),
OffseasonRebate FLOAT,
AwardPointsPerMile FLOAT,
BaggageTicketCode INT,
FOREIGN KEY `fk_Product_to_Product` (BaggageTicketCode) REFERENCES Product(ProductID),
InsuranceName VARCHAR(255),
SpecialTypeOfService VARCHAR(255),
RefreshmentName VARCHAR(255),
RefreshmentCost FLOAT
);
CREATE TABLE Invoice
(
InvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(InvoiceID),
InvoiceCode VARCHAR(255),
CustomerCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Customer` (CustomerCode) REFERENCES Customer(CustomerID),
SalespersonCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Person` (SalespersonCode) REFERENCES Person(PersonID),
InvoiceDate VARCHAR(255)
);
CREATE TABLE ProductInvoice
(
ProductInvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductInvoiceID),
ProductID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Product` (ProductID) REFERENCES Product(ProductID),
InvoiceID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Invoice`(InvoiceID) REFERENCES Invoice(InvoiceID),
TravelDate VARCHAR(255),
NumOfPassengers INT NOT NULL,
Seat VARCHAR(255),
TicketNote VARCHAR(255)
);
CREATE TABLE Passenger
(
PassengerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PassengerID),
PersonID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_Person` (PersonID) REFERENCES Person(PersonID),
IdentityNumber VARCHAR(255),
PassengerAge INT NOT NULL,
PassengerNationality VARCHAR(255),
ProductInvoiceID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_ProductInvoice` (ProductInvoiceID)
REFERENCES ProductInvoice(ProductInvoiceID)
);
This is the error I get:
Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails
and it fails on the DROP TABLE for Invoice.
Disable foreign key checks or.
Drop the whole database or.
Run the script twice or.
Drop the fk constraints first.
Mysql workbench will generate a script for you if you highlight all if the tables and create a drop script. Same with the mysql dump utility.
How to temporarily disable a foreign key constraint in MySQL?
I am working library project. I want to create a database and table, but I do not know why my codes do not work. I check all create table syntax no errors.
Could you teach me how to fix them?
DROP DATABASE IF EXISTS LIBRARYS;
CREATE DATABASE LIBRARYS;
USE LIBRARYS;
DROP TABLE IF EXISTS BOOK;
CREATE TABLE BOOK
(
title VARCHAR(50) NOT NULL,
author VARCHAR(30),
BookId INT auto_increment,
ISBN INT,
Edition VARCHAR(50),
YearBought INT,
Category VARCHAR (30),
LibraryBranchID INT auto_increment,
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
);
DROP TABLE IF EXISTS Person;
CREATE TABLE Person
(PersonId INT AUTO_INCREMENT,
uNAME VARCHAR(30) NOT NULL,
age INT,
UserType VARCHAR (30),
PreferredBranch INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (PersonId),
FOREIGN KEY ( PreferredBranch) references LibraryBranch(LibraryBranchID)
) ;
ALTER table Person AUTO_INCREMENT = 1001;
DROP TABLE IF EXISTS LOAN;
CREATE TABLE LOAN
(LoanId INT auto_increment,
Pid INT,
Bid INT,
loanDate DATE DEFAULT '0000-00-00',
overdue BOOLEAN DEFAULT FALSE,
PRIMARY KEY(LoanId),
FOREIGN KEY (Pid) references Person (PersonId),
FOREIGN KEY (Bid) references Book(BookId)
) ;
DROP TABLE IF EXISTS LibraryBranch ;
CREATE TABLE LibraryBranch
(uID INT AUTO_INCREMENT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
DROP TABLE IF EXISTS Rating;
CREATE TABLE Rating
(RatingId INT ,
RatingDate INT,
BookId INT,
PersonId INT,
Stars BOOLEAN DEFAULT FALSE,
PRIMARY KEY(RatingId),
FOREIGN KEY (PersonId) references Person (PersonId),
FOREIGN KEY (BookId) references BOOK(BookId)
) ;
LOAD DATA LOCAL INFILE '' INTO TABLE BOOK;
LOAD DATA LOCAL INFILE '' INTO TABLE Person;
LOAD DATA LOCAL INFILE '' INTO TABLE LOAN;
Here I got those results
1 row(s) affected
0 row(s) affected
0 row(s) affected, 1 warning(s): 1051 Unknown table 'librarys.book'
Error Code: 1075. Incorrect table definition; there can be only one auto column and it must be defined as a key
CREATE TABLE LibraryBranch should be before your call FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
CREATE TABLE BOOK
(
...
BookId INT auto_increment,
...
LibraryBranchID INT auto_increment,
...
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
);
and if FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName) this LibraryBranchID can't be auto_increment
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName) wrong field BranchName called should be LibraryBranchID:
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(LibraryBranchID)
and there is no need to DROP TABLE IF EXISTS each table since you just created the database
UPDATE http://sqlfiddle.com/#!9/86bb96
CREATE TABLE LibraryBranch
(uID INT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
CREATE TABLE BOOK
(
title VARCHAR(50) NOT NULL,
author VARCHAR(30),
BookId INT auto_increment,
ISBN INT,
Edition VARCHAR(50),
YearBought INT,
Category VARCHAR (30),
LibraryBranchID INT ,
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(LibraryBranchID)
);
CREATE TABLE Person
(PersonId INT AUTO_INCREMENT,
uNAME VARCHAR(30) NOT NULL,
age INT,
UserType VARCHAR (30),
PreferredBranch INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (PersonId),
FOREIGN KEY ( PreferredBranch) references LibraryBranch(LibraryBranchID)
) ;
ALTER table Person AUTO_INCREMENT = 1001;
CREATE TABLE LOAN
(LoanId INT auto_increment,
Pid INT,
Bid INT,
loanDate DATE DEFAULT '0000-00-00',
overdue BOOLEAN DEFAULT FALSE,
PRIMARY KEY(LoanId),
FOREIGN KEY (Pid) references Person (PersonId),
FOREIGN KEY (Bid) references Book(BookId)
) ;
CREATE TABLE Rating
(RatingId INT ,
RatingDate INT,
BookId INT,
PersonId INT,
Stars BOOLEAN DEFAULT FALSE,
PRIMARY KEY(RatingId),
FOREIGN KEY (PersonId) references Person (PersonId),
FOREIGN KEY (BookId) references BOOK(BookId)
) ;
In this code:
CREATE TABLE LibraryBranch
(uID INT AUTO_INCREMENT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
You made uID an auto column, but LibraryBranchID is the PK.
You cannot have two auto_increment fields in mysql innodb tables.
You can use trigger for second field if you want it to auto increment.