Can not CREATE TABLE? - 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.

Related

MYSQL 1215 cannot add foreign constraint

So I don't know why i cant add the foreign constraint in the table ORDER_LINE, i made sure all the types are correct. Please help, it keeps on giving me the error
Error Code: 1215. Cannot add foreign key constraint
CREATE TABLE IF NOT EXISTS Customer (
Customer_ID int NOT NULL AUTO_INCREMENT,
Customer_Name VARCHAR(50) NOT NULL,
Customer_Age INT UNIQUE,
Customer_Address VARCHAR(255),
Customer_City VARCHAR(255),
Customer_State VARCHAR(50),
Customer_Zip VARCHAR(20),
PRIMARY KEY(Customer_ID)
);
CREATE TABLE IF NOT EXISTS Sales_order (
Order_ID int AUTO_INCREMENT,
Order_date DATE,
Customer_ID int,
PRIMARY KEY(Order_ID),
FOREIGN KEY(Customer_ID) REFERENCES Customer(Customer_ID) ON DELETE
CASCADE
);
CREATE TABLE IF NOT EXISTS Products (
Product_ID int AUTO_INCREMENT,
Product_Description VARCHAR(255),
Product_Finish VARCHAR(50),
Standard_Price DECIMAL,
Product_Line_ID INT,
PRIMARY KEY(Product_ID)
);
CREATE TABLE IF NOT EXISTS ORDER_LINE (
Order_ID int,
Product_ID int,
Ordered_Quantity int,
PRIMARY KEY(Order_ID, Product_ID),
FOREIGN KEY(Order_ID) REFERENCES Sales_order(Order_ID) ON DELETE SET NULL,
FOREIGN KEY(Product_ID) REFERENCES Products(Product_ID)
);
This might be because primary key columns are made NOT NULL, so your ON DELETE SET NULL is trying to set an invalid value.
EDIT: In fact, I just tested and that does seem to be the issue -- it creates the table if I remove either the SET NULL or the primary key.

Error 1215 in MySQL when adding foreign keys

I'm getting an error when adding Foreign Keys to the system, the error says Cannot add foreign key constraint and the code that I have is:
DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;
CREATE TABLE Formed(
FormedID int NOT NULL,
YearFormed int,
CountryFormed varchar(50),
CityFormed varchar(50),
BandMembers varchar(400),
PRIMARY KEY(FormedID))
ENGINE=InnoDB;
CREATE TABLE Track (
TrackID int NOT NULL,
AlbumID int NOT NULL,
Songs varchar (100),
TrackNumber varchar (20),
Title varchar (30),
TrackDuration varchar (4),
PRIMARY KEY (TrackID))
ENGINE=InnoDB;
CREATE TABLE Album(
AlbumID int NOT NULL,
TrackID int NOT NULL,
BandID int NOT NULL,
KEY(TrackID),
KEY(BandID),
Price varchar(5),
PublicationDate varchar(11),
Title varchar(30),
Genre varchar (36),
PRIMARY KEY(AlbumID))
ENGINE=InnoDB;
CREATE TABLE Band(
BandID int NOT NULL,
AlbumID int NOT NULL,
KEY(AlbumID),
RecordLabel varchar(50),
PRIMARY KEY(BandID))
ENGINE=InnoDB;
CREATE TABLE Customers (
CustomerID int NOT NULL,
CName varchar (20),
CPhone int (11),
CEmail varchar (50),
CPPaid varchar (50),
CPDate date,
PRIMARY KEY (CustomerID))
ENGINE=InnoDB;
ALTER TABLE Track
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Band
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
I'm new to adding Foreign Keys into MySQL and I don't understand how I'm getting this error. I'm getting the error when it hits the line ALTER TABLE Track
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE; and I believe it will create the same error for the lines that come after it too.
You cannot provide ON DELETE SET NULL for non-nullable fields.

MySQL Error 1217 [duplicate]

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?

SQL create table primary key and foreign key syntax

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.

Unable To Create Table, Unsure of what to do (Error: 150)

I am creating several tables at once and I keep getting the error(150):
#1005 - Can't create table 'waget.tour' (errno: 150)
and despite me knowing what the error is, I simply can't fix it. All tables references in the table "tour" are all there and exist, with keys where Foreign keys are referenced. I've checked it over plenty of times, and simply can't find anything. Can anyone see what I am doing wrong?
(Getting error when creating the table "tours")
CREATE TABLE IF NOT EXISTS tourPayment(
tourPaymentNumber int,
tourCost int(7),
PRIMARY KEY (tourPaymentNumber),
KEY (tourCost)
);
CREATE TABLE IF NOT EXISTS hotel(
hotelID int AUTO_INCREMENT,
hotelName varchar(30),
PRIMARY KEY (hotelID),
KEY (hotelName)
);
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutation)
);
CREATE TABLE IF NOT EXISTS customer(
custID int AUTO_INCREMENT,
custSalutation varchar(4),
custLname varchar(30),
custAdd varchar(100),
custPcode varchar(4),
custState varChar(20),
custPhone varchar(10),
custHotel varchar(30),
PRIMARY KEY (custID),
FOREIGN KEY (custHotel) REFERENCES hotel(hotelName),
FOREIGN KEY (custSalutation) REFERENCES salutation(salutation)
);
CREATE TABLE IF NOT EXISTS bus(
busID int AUTO_INCREMENT,
busMake varchar(30),
busSeats varchar(3),
PRIMARY KEY (busID)
);
CREATE TABLE IF NOT EXISTS busDriver(
driverID int AUTO_INCREMENT,
driverName varchar(20),
driverEmail varchar(40),
busID int,
PRIMARY KEY (driverID),
FOREIGN KEY (busID) REFERENCES bus(busID)
);
CREATE TABLE IF NOT EXISTS tour(
DailyTourID int AUTO_INCREMENT,
NoOfPeople int(3),
tourDate DATE,
tourTime TIME,
tourName varchar(30),
tourCost int(7),
tourDriverID varchar(20),
PRIMARY KEY (DailyTourID),
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID),
FOREIGN KEY (tourCost) REFERENCES tourPayment(tourCost)
);
CREATE TABLE IF NOT EXISTS TourCustLink(
TourCustLinkID int AUTO_INCREMENT,
TourID int,
custID int,
PRIMARY KEY (TourCustLinkID),
FOREIGN KEY (TourID) REFERENCES tour(DailyTourID),
FOREIGN KEY (custID) REFERENCES customer(custID)
);
Here is your problem:
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID)
references an INT but is declared as varchar(20)
AUTO_INCREMENT fields all need to be PRIMARY KEY's, so try changing salutation to be
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
PRIMARY KEY (salutationID),
KEY (salutation)
);
Additionally in tour you have the wrong datatype for tourDriverID, it should be INT to match the referenced key
CREATE TABLE IF NOT EXISTS tour(
DailyTourID int AUTO_INCREMENT,
NoOfPeople int(3),
tourDate DATE,
tourTime TIME,
tourName varchar(30),
tourCost int(7),
tourDriverID INT,
PRIMARY KEY (DailyTourID),
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID),
FOREIGN KEY (tourCost) REFERENCES tourPayment(tourCost)
);
SQL fiddle example in full can be found here : http://sqlfiddle.com/#!2/840b9
Actually it's easy to try and create tables one by one and you would get a better error message..
Your Problem is the table salutation since you have to define the AUTO_INCREMENT field (in your case salutationID) as KEY and not the fieldsalutation`
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutationID) -- here is your error
);
Is this the code you ran? if so, the error is about the AUTO_INCREMENT needing to be a Key.
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutation)
);
Try:
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutationID)
);
and make other a FOREIGN KEY if you need to.
Cheers.