Adding constraints to tables in MySQL - mysql

I'm creating a db for a theater. It currently has only two tables: shows and movies.
Each movie has (besides the auto increment id int not null), a unique string id (also not null), which I would like to use as a foreign key inside of the shows table. Its giving me:
Error Code: 1215. Cannot add foreign key constraint
Here is my query:
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE movies CASCADE;
DROP TABLE shows CASCADE;
SET FOREIGN_KEY_CHECKS=1;
CREATE TABLE movies (
`movies_id` INT auto_increment,
`movie_id` VARCHAR(18) NOT NULL,
`title` VARCHAR(100),
`original_title` VARCHAR(100),
`punchline` VARCHAR(250),
`genre` VARCHAR(60),
`year` INT,
`duration` INT,
`url` VARCHAR(150),
`poster` VARCHAR(150),
`director` VARCHAR(45),
`producer` VARCHAR(45),
`writer` VARCHAR(100),
`cast` VARCHAR(500),
`distributor` VARCHAR(45),
`language` VARCHAR(45),
`country` VARCHAR(100),
`localization` VARCHAR(45),
`plot_outline` VARCHAR(800),
`sum_of_scores` DOUBLE,
`num_of_scores` DOUBLE,
PRIMARY KEY (`movies_id`));
CREATE TABLE shows (
`shows_id` INT auto_increment,
`show_id` VARCHAR(18),
`date` DATE,
`time` DATETIME,
`city` VARCHAR(45),
`center` VARCHAR(45),
`theater` VARCHAR(45),
`movies_movie_id` VARCHAR(18),
PRIMARY KEY (`shows_id`));
ALTER TABLE shows
ADD CONSTRAINT fk_shows_movies FOREIGN KEY
(`movies_movie_id`) REFERENCES movies(`movie_id`);

Foreign keys must refer to primary key/ unique key in parent table. In your case, you have two columns movies_id and movie_id, and you have defined movies_id as primary key. But, your foreign key is trying to reference movie_id column. You will need to make this column unique in this circumstance to create your foreign key.

Related

Cannot add foreign key restraint error in MySQL?

I keep getting the same error in MySQL and i'm not sure what I missing here.
I am very new to working with MySQL, so I am not sure if I need to add a constraint maybe? If I do not need a constraint, is there another way to go about defining the relationships? Below is my syntax:
DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (
`art_id` INT NOT NULL,
`art_name` VARCHAR(45) NULL,
`artist_id` INT(11) NULL,
`location_id` INT(11) NULL,
`employee_id` INT(11) NULL,
`art_received` DATE NULL,
primary key (`art_id`),
FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)
);
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),
primary key (`employee_id`)
);
DROP TABLE IF EXISTS `artist`;
CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),
primary key (`artist_id`)
);
DROP TABLE IF EXISTS `location`;
CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,
primary key (`location_id`)
);
simply switch the order of which table gets created first. when you created
table art the other three table still have not be created so it doesn't know what artist(artist_id),location(location_id),employee(employee_id)
are.
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),
primary key (`employee_id`)
);
DROP TABLE IF EXISTS artist;
CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),
primary key (`artist_id`)
);
DROP TABLE IF EXISTS `location`;
CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,
primary key (`location_id`)
);
DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (
`art_id` INT NOT NULL,
`art_name` VARCHAR(45) NULL,
`artist_id` int(11) NULL,
`location_id` int(11) NULL,
`employee_id` int(11) NULL,
`art_received` DATE NULL,
primary key (`art_id`),
FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)
);
And welcome to StackOverflow. if you find this answer or any other answer helpful please mark it as the solution. That way would help the community and if fellow programmers run into the same problem as you did in the future they can find the solution easily.

Syntax Error in MySQL - Same syntax worked in earlier table

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 ...

How to change sql code to mysql

i have this script running on sql, but i need to optimize it to mysql using the workbench, but it shows me an error in the foreign key and i don't know how to change it.
create table EspecialidadesMedicas(
IdEspecialidad int(4) primary key,
DescripcionEspecialidad varchar(30));
create table Doctores(
IdDoctor int(5) PRIMARY KEY,
NombreDoctor varchar(30),
Salario int(12.2),
Especialidad int(4),citascitas
Especialidad FOREIGN KEY references EspecialidadesMedicas(IdEspecialidad));
The following is working syntax:
create table EspecialidadesMedicas (
IdEspecialidad int(4) primary key,
DescripcionEspecialidad varchar(30)
);
create table Doctores(
IdDoctor int(5) PRIMARY KEY,
NombreDoctor varchar(30),
Salario int(12),
Especialidad int(4),
citascitas varchar(30),
constraint fk_Especialidad FOREIGN KEY (Especialidad) references EspecialidadesMedicas(IdEspecialidad)
);

mysql error 1064 when creating table. What can I check for?

I'm getting an ERROR 1064 (42000) at line 21, which is VIN_Number in Vehicle table. Entity Inventory gets built without a problem, VIN_Number is of type varchar(17) for all occurrences. I believe the tables are being built in the correct order. I can't find any spelling or punctuation errors. I'm out of ideas of things I should checked. What is it that I'm missing?
Note: I getting an error for Invoice as well, but I know that it can't be created until Vehicle gets created.
ALTER TABLE Vehicle DROP FOREIGN KEY fk_Veh_Vehicle_TypeID;
ALTER TABLE Inventory DROP FOREIGN KEY fk_Inv_Vehicle_TypeID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Customer_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Sales_Person_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_VIN_Number;
DROP TABLE IF EXISTS Vehicle, VehicleType,
Invoice, Customer, SalesPerson, Inventory;
CREATE TABLE VehicleType (
Vehicle_TypeID int NOT NULL,
Veh_Make varchar(15),
Veh_Model varchar(15),
Veh_Year int,
PRIMARY KEY (Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Vehicle (
VIN_Number varchar(17) NOT NULL,
Vehicle_TypeID int NOT NULL,
Condition varchar(10),
Color varchar(8),
PRIMARY KEY (VIN_Number),
CONSTRAINT fk_Veh_Vehicle_TypeID FOREIGN KEY(Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Inventory (
Stock_ID int NOT NULL,
Vehicle_TypeID int NOT NULL,
Quantity int,
PRIMARY KEY (Stock_ID),
CONSTRAINT fk_Inv_Vehicle_TypeID FOREIGN KEY (Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Customer (
Customer_ID varchar(10) NOT NULL,
Cus_LastName varchar(15),
Cus_FirstName varchar(15),
Cus_Street varchar(20),
Cus_City varchar(15),
Cus_Zip varchar(5),
Cus_Phone varchar(10),
PRIMARY KEY (Customer_ID)
) Engine=InnoDB;
CREATE TABLE SalesPerson (
Sales_Person_ID varchar(10) NOT NULL,
Sal_LastName varchar(15),
Sal_FirstName varchar(15),
Sal_Street varchar(15),
Sal_City varchar(15),
Sal_Zip varchar(5),
Sal_Phone varchar(10),
Sal_Years_Worked int,
Sal_Commission_Rate float(4),
PRIMARY KEY (Sales_Person_ID)
) Engine=InnoDB;
CREATE TABLE Invoice (
Invoice_ID varchar(10) NOT NULL,
Customer_ID varchar(10) NOT NULL,
Sales_Person_ID varchar(10) NOT NULL,
VIN_Number varchar(17) NOT NULL,
Price float(10),
PRIMARY KEY (Invoice_ID),
CONSTRAINT fk_Customer_ID FOREIGN KEY (Customer_ID)
REFERENCES Customer(Customer_ID),
CONSTRAINT fk_Sales_Person_ID FOREIGN KEY (Sales_Person_ID)
REFERENCES SalesPerson(Sales_Person_ID),
CONSTRAINT fk_VIN_Number FOREIGN KEY (VIN_Number)
REFERENCES Vehicle(VIN_Number)
) Engine=InnoDB;
In the definition of the Vehicle table you have a column named condition which is a reserved keyword in MySQL (reference). Either use another name for the column or enclose it in backticks like this: `condition`
Using keywords (reserved or not) for object names is generally something you want to avoid.

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.