Can't figure out why mySql database syntax won't compile - mysql

I'm getting this syntax error for a DB I am writing for my own personal project and am unsure why this error is occuring, any help would be much appreciated! The desired result is just compilation at this point, and the error is a simple syntax error.
The problem table is the Team table.
Error Code: 1215: Cannot add foreign key contraint.
-- CREATE DATABASE basketBall;
DROP TABLE LEAGUE;
-- DROP TABLE TEAM;
DROP TABLE SESSION;
CREATE TABLE LEAGUE (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
CREATE TABLE SESSION (
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(year, season, division),
CONSTRAINT chk_season CHECK (season IN ('Fall', 'Winter', 'Spring', 'Summer'))
);
CREATE TABLE TEAM (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
season VARCHAR(50) NOT NULL,
year INT NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(year) REFERENCES SESSION(year),
FOREIGN KEY(division) REFERENCES SESSION(division)
);
CREATE TABLE PLAYER (
id INT NOT NULL AUTO_INCREMENT,
fname VARCHAR(30) NOT NULL,
lname VARCHAR(30) NOT NULL,
lid INT,
PRIMARY KEY(id)
);
CREATE TABLE GAME (
id INT NOT NULL AUTO_INCREMENT,
time VARCHAR(5),
court VARCHAR(20),
date DATE,
PRIMARY KEY(id)
);
CREATE TABLE STATS (
pid INT NOT NULL,
gid int NOT NULL,
pts INT NOT NULL,
fgm INT NOT NULL,
fga INT NOT NULL,
fta INT NOT NULL,
ftm INT NOT NULL,
3fgm INT NOT NULL,
3fga INT NOT NULL,
oreb INT NOT NULL,
dreb INT NOT NULL,
ast INT NOT NULL,
stl INT NOT NULL,
blk INT NOT NULL,
turnover INT NOT NULL,
eff INT NOT NULL,
pf INT NOT NULL,
min INT NOT NULL,
PRIMARY KEY(pid, gid),
FOREIGN KEY(pid) REFERENCES PLAYER(id),
FOREIGN KEY(gid) REFERENCES GAME(id)
);
CREATE TABLE Players_on_Team (
tid INT NOT NULL,
pid INT NOT NULL,
PRIMARY KEY(tid, pid),
FOREIGN KEY(tid) REFERENCES TEAM(id)
);
CREATE TABLE League_Sessions (
lid INT NOT NULL,
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(lid, year, season, division),
FOREIGN KEY(lid) REFERENCES LEAGUE(id)
);

A column that you reference in a foreign key must be indexed. These two foreign keys in TEAM:
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(division) REFERENCES SESSION(division)
refer to columns that don't have indexes of their own. They're parts of a multi-column index, but only a prefix of a multi-column index acts as an index on those specific columns.
You could add separate indexes on the season and division columns to the SESSION table. But it would probably be more appropriate to make a multi-column foreign key:
FOREIGN KEY (year, season, division) REFERENCES SESSION(year, season, division)

I just tried it and it executes without any errors.

Related

mysql - cannot add foreign key constraint when creating a table

I'm new to sql.
I get this error when I try to create foreign keys:
cannot add foreign key constraint
when I'm trying to create the ORDERS table. here is my code:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4), w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4), customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
I put the ORDERS (where I have the problem) on different lines to make it easier to you to read.
I search here for an answer, but didn't found anything specific that answer my question.
anyone got any idea what the problem is? thank you!
The problem is that you are trying to create a FOREIGN KEY relationship to a field in the WORKERS and CUSTOMERS tables that aren't set up as a PRIMARY KEY.
The FOREIGN KEY needs to be pointing to a PRIMARY KEY. Change your create script to the following:
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
A word of caution, though. I would recommend not using VARCHAR (4) as a PRIMARY KEY field. I would recommend using an INT AUTO_INCREMENT instead.
The column of the referenced table should be declared as primary key to assign a foreign key. For your orders table, WORKERS(w_id) and CUSTOMERS(customer_id) are not declared as primary key, hence you get the error.
Modified Statements:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
SQLFiddle Demo

MySQL error code 1005 / errno: 150

I'm using a XAMPP 5.6.19-0 as a MySQL Database server and managing via MySQL Workbench (Mac OS 10.11.3). I'm trying to create some tables, with foreign keys, and im getting this error:
Error Code: 1005. Can't create table imobiliaria24h.proprietario (errno: 150 "Foreign key constraint is incorrectly formed")
This is the code I'm trying to use:
CREATE TABLE IF NOT EXISTS PROPRIETARIO (
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS IMOVEL(
ENDERECO VARCHAR(100) NOT NULL,
TIPO ENUM('ALUGUEL', 'VENDA'),
INQUILINO_CPF INT,
PROPRIETARIO_CPF INT,
VALOR_ALUGUEL_PRECOVENDA INT NOT NULL,
NUM_QUARTOS INT NOT NULL,
METRAGEM INT NOT NULL,
NUM_BANHEIROS INT NOT NULL,
VALOR_CONDOMINIO INT NOT NULL,
IDADE INT NOT NULL,
HORA_REGISTRO TIME NOT NULL,
PRIMARY KEY(ENDERECO),
FOREIGN KEY (INQUILINO_CPF) REFERENCES INQUILINO(CPF),
FOREIGN KEY (PROPRIETARIO_CPF) REFERENCES PROPRIETARIO(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS INQUILINO(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
FIADOR BOOLEAN NOT NULL,
INADIMPLENCIA INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS CORRETOR(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
ANOS_CASA SMALLINT NOT NULL,
TRABALHA_FDS BOOLEAN NOT NULL,
TRABALHA_NOITE BOOLEAN NOT NULL,
PRIMARY KEY (CPF)
)ENGINE=InnoDB;
The interesting thing is that, if I create the table separately, only the ones that references each other, for example, I created first PROPRIETARIO and CORRETOR, second INQUILINO, and at last IMOVEL, and this way everything worked. I'm not understanding why I'm getting the error creating them all together in a "single command".
Are you running that exact script? If so, it looks like you're trying to create the foreign keys before you've actually crated the tables they're referencing.
Try changing the order in which you build them.
CREATE TABLE IF NOT EXISTS CORRETOR(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
ANOS_CASA SMALLINT NOT NULL,
TRABALHA_FDS BOOLEAN NOT NULL,
TRABALHA_NOITE BOOLEAN NOT NULL,
PRIMARY KEY (CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS PROPRIETARIO (
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS INQUILINO(
NOME VARCHAR(30) NOT NULL,
CPF INT NOT NULL,
TELEFONE INT NOT NULL,
FIADOR BOOLEAN NOT NULL,
INADIMPLENCIA INT NOT NULL,
CORRETOR_CPF INT NOT NULL,
PRIMARY KEY (CPF),
FOREIGN KEY (CORRETOR_CPF) REFERENCES CORRETOR(CPF)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS IMOVEL(
ENDERECO VARCHAR(100) NOT NULL,
TIPO ENUM('ALUGUEL', 'VENDA'),
INQUILINO_CPF INT,
PROPRIETARIO_CPF INT,
VALOR_ALUGUEL_PRECOVENDA INT NOT NULL,
NUM_QUARTOS INT NOT NULL,
METRAGEM INT NOT NULL,
NUM_BANHEIROS INT NOT NULL,
VALOR_CONDOMINIO INT NOT NULL,
IDADE INT NOT NULL,
HORA_REGISTRO TIME NOT NULL,
PRIMARY KEY(ENDERECO),
FOREIGN KEY (INQUILINO_CPF) REFERENCES INQUILINO(CPF),
FOREIGN KEY (PROPRIETARIO_CPF) REFERENCES PROPRIETARIO(CPF)
)ENGINE=InnoDB;

Problems with MYSQL Error 150 during table creation

I looked up other posts about this problem (there are a lot of them), but I have to say nothing worked so far for me. The only thing did not try was to disable foreign check.
My Problem:
When I try to create two simple tables I got the error 150 and I can't figure out why.
My Code so far:
drop table if exists SENSOR;
drop table if exists SENSOR_DATEN;
create table SENSOR (
SENSOR_ID int not null auto_increment,
SENSOR_NAME varchar(100),
SENSOR_POSX float not null,
SENSOR_POSY float not null,
SENSOR_EINHEIT varchar(100) not null,
primary key (SENSOR_ID)
);
commit;
create table SENSOR_DATEN (
SENSOR_DATEN_ID int not null auto_increment,
SENSOR_ID int not null,
SENSOR_DATEN_WERT varchar(100),
SENSOR_TYP varchar(100) not null,
primary key (SENSOR_DATEN_ID),
foreign key(SENSOR_ID) references SENSOR(SENSOR_ID),
foreign key(SENSOR_TYP) references SENSOR(SENSOR_EINHEIT)
);
commit;
My main problem is to understand the Problem. I got a way bigger database which is nearly identical but there are no problems. Here is the Code for the Database which works fine:
drop table if exists AUSGELIEHEN_FILM;
drop table if exists AUSGELIEHEN_SPIEL;
drop table if exists KUNDE;
drop table if exists FILM;
drop table if exists SPIEL;
create table KUNDE (
KUNDE_ID int not null auto_increment,
KUNDE_VNAME varchar(100),
KUNDE_NAME varchar(100),
KUNDE_ADRESSE varchar(100),
KUNDE_PLZ int not null,
primary key (KUNDE_ID)
);
create table FILM (
FILM_ID int not null auto_increment,
FILM_NAME varchar(100),
FILM_GENRE varchar(50),
FILM_FSK int not null,
FILM_BEWERTUNG int not null,
FILM_ANZAHL int not null,
FILM_MEDIUM varchar(50),
primary key (FILM_ID)
);
create table SPIEL (
SPIEL_ID int not null auto_increment,
SPIEL_NAME varchar(100),
SPIEL_GENRE varchar(50),
SPIEL_FSK int not null,
SPIEL_BEWERTUNG int not null,
SPIEL_ANZAHL int not null,
SPIEL_PLATFORM varchar(50),
primary key (SPIEL_ID)
);
create table AUSGELIEHEN_FILM (
AUSGELIEHEN_FILM_ID int not null auto_increment,
KUNDE_ID int not null,
FILM_ID int not null,
AUSGELIEHEN_ANZAHL int not null,
primary key(AUSGELIEHEN_FILM_ID),
foreign key(KUNDE_ID) references KUNDE(KUNDE_ID),
foreign key(FILM_ID) references FILM(FILM_ID)
);
create table AUSGELIEHEN_SPIEL(
AUSGELIEHEN_SPIEL_ID int not null auto_increment,
KUNDE_ID int not null,
SPIEL_ID int not null,
AUSGELIEHEN_ANZAHL int not null,
primary key(AUSGELIEHEN_SPIEL_ID),
foreign key(KUNDE_ID) references KUNDE(KUNDE_ID),
foreign key(SPIEL_ID) references SPIEL(SPIEL_ID)
);
commit;
Your table SENSOR_DATEN declares a foreign key that references SENSOR's column SENSOR_EINHEIT. This column is not defined as being unique, and thus can not have a foreign key pointing to it. Hence, your failure.
You could amend the declaration of SENSOR to make the column unique:
create table SENSOR (
SENSOR_ID int not null auto_increment,
SENSOR_NAME varchar(100),
SENSOR_POSX float not null,
SENSOR_POSY float not null,
SENSOR_EINHEIT varchar(100) not null,
primary key (SENSOR_ID),
unique (SENSOR_EINHEIT)
);
Or alternatively, apply it post-factum to an existing table:
alter table SENSOR add constraint SENSOR_EINHEIT_UNQ unique(SENSOR_EINHEIT);

Cannot Add foreign key constraint Error 1215

I am using Workbench 6.0 and having a frustrating issue I am new to SQl and would like to keep this as simple as possible at this point, I believe my tables are ordered properly to add contraints except for my TICKET table, no idea how to find what foreign key is having problems.
CREATE TABLE IF NOT EXISTS ACTION_TYPE (
ActionCode int primary key,
Description char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS OFFICER (
PersonnelNo int primary key,
OfficerLName char(50) not null,
OfficerFName char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS DRIVER (
DriverLicenseNo int primary key,
DriverLastName char(50) not null,
DriverFirstName char(50) not null,
DriverAddress char(50) not null,
DriverCity char(50) not null,
DriverProv char(50) not null,
DriverPostalCode varchar(6) not null,
DriverGender char(1) not null,
DriverBirthDate Date not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS REGISTERED_OWNER (
RegOwnerID int primary key auto_increment,
RegOwnerLName char(50) not null,
RegOwnerFName char(50) not null,
RegOwnerAddress char(50) not null,
RegOwnerCity char(50) not null,
RegOwnerProv char(50) not null,
RegOwnerPostalCode varchar(6) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VEHICLE_TYPE (
VehicleType int primary key,
VehicleDescription char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VEHICLE (
VehicleLicense int primary key,
ProvinceIssued char(2) not null,
VehicleYear int not null,
VehicleMake char(10) not null,
VehicleType int not null,
index (VehicleType),
foreign key (VehicleType)
references VEHICLE_TYPE (VehicleType)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS TICKET ( <-----this table calling the error
TicketNo int primary key auto_increment,
TicketDateTime datetime not null,
TicketLocationCity char(50) not null,
TicketLocationProv char(50) not null,
TicketLocationRoad char(50) not null,
PersonnelNo int not null,
VehicleLicense int not null,
ActionCode int not null,
RegOwnerID int not null,
DriversLicenseNo int not null,
index (PersonnelNo),
foreign key (PersonnelNo)
references OFFICER (PersonnelNo),
index (VehicleLicense),
foreign key (VehicleLicense)
references VEHICLE (VehicleLicense),
index (ActionCode),
foreign key (ActionCode)
references ACTION_TYPE (ActionCode),
index (RegOwnerID),
foreign key (RegOwnerID)
references REGISTERED_OWNER (RegOwnerID),
index (DriversLicenseNo),
foreign key (DriversLicenseNo)
references DRIVER (DriversLicenseNo)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VIOLATION_TYPE (
ViolationCode int primary key auto_increment,
ViolationDesc char(50) not null,
ViolationCurrFineAmt int not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VIOLATION (
ViolationNo int primary key auto_increment,
TicketNo int not null,
ViolationCode int not null,
AppliedFineAmount int not null,
index (TicketNo),
foreign key (TicketNo)
references TICKET (TicketNo),
index (ViolationCode),
foreign key (ViolationCode)
references VIOLATION_TYPE (ViolationCode)
)ENGINE=InnoDB;
Spelling mistake on DriverLicenseNo in TICKET table ane
DriversLicenseNo in DRIVER table

#1005 - Can't create table 'workswell_database.skoleni' Novice user with MySQL

sorry for my stupid question,but I do database in MySQL and was so happy,when i finished.Unfortunately,I had found a lot of mistakes in my database n when i will properly fix a bug,so i've another. Also,this is my Database and that guy what really boring right now,please write about my bugs and solution for them.I novice as a programmer and this database i do about 4 days !
CREATE TABLE`Skoleni` (
`sk_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Cena` MEDIUMINT NOT NULL,
`Obsazenost` text NOT NULL,
`Kapacita` datetime NOT NULL,
`Popis` text,
`Prerekvizity` text,
`Certifikat` MEDIUMINT NOT NULL,
PRIMARY KEY (`sk_id`),
FOREIGN KEY (`sk_id`) REFERENCES Skoleni_has_Termin(`Skoleni_sk_id`),
FOREIGN KEY (`sk_id`) REFERENCES Skoleni_has_Uzivatel(`Skoleni_sk_id`)
);
CREATE TABLE `Skoleni_has_Termin`(
`Skoleni_sk_id`INT NOT NULL UNIQUE,
`Termin_ter_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Skoleni_sk_id`)
);
CREATE TABLE `Termin` (
`ter_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Datum_cas` DATETIME NOT NULL,
`Misto_mo_id` INT NOT NULL,
PRIMARY KEY (`ter_id`),
FOREIGN KEY (`ter_id`) REFERENCES Skoleni_has_Termin(`Termin_ter_id`)
);
CREATE TABLE `Misto` (
`mo_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`ulice` MEDIUMINT NOT NULL,
`cislo_popisne` MEDIUMINT NOT NULL,
`lat` FLOAT (10,6) NOT NULL,
`lng` FLOAT (10,6) NOT NULL,
PRIMARY KEY (`mo_id`)
)ENGINE = MYISAM;
SELECT TABLE.Misto(
INSERT (`ulice`, `cislo_popisne`, `lat`, `lng`),
VALUES (`dr_Zikmunda_Wintra_376_5``16000 Praha 6 Bubenec``14.407438``50.101049`)
);
CREATE TABLE `Skoleni_has_Uzivatel` (
`Skoleni_sk_id` INT NOT NULL UNIQUE,
`Uzivatel_uziv_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Skoleni_sk_id`)
);
CREATE TABLE `Uzivatel` (
`uziv_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Jmeno` VARCHAR(30) NOT NULL,
`Typ` MEDIUMINT UNIQUE,
`Heslo` VARCHAR(32) NOT NULL,
`Potvrzeni` VARCHAR(1) NOT NULL,
PRIMARY KEY (`uziv_id`),
FOREIGN KEY (`uziv_id`) REFERENCES Skoleni_has_Uzivatel(`Uzivatel_uziv_id`)
);
CREATE TABLE `Skoleni_has_Lektor` (
`Skoleni_sk_id` INT NOT NULL UNIQUE,
`Lektor_lek_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Lektor_lek_id`)
);
CREATE TABLE `Lektor` (
`lek_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Titul'pred'` VARCHAR(10) NOT NULL,
`Jmeno` VARCHAR(20) NOT NULL,
`Prijmeni` VARCHAR(20) NOT NULL,
`Titul'za'` VARCHAR(10),
`Firma` VARCHAR(30),
`Rodne cislo` CHAR(11) NOT NULL,
`Datum narozeni` DATE NOT NULL,
PRIMARY KEY (`lek_id`)
);
CREATE TABLE `Firma` (
`fir_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`E-mail` VARCHAR(15) NOT NULL,
`Telefon` VARCHAR(15) NOT NULL,
`Web` VARCHAR(30),
`IC` CHAR(8) NOT NULL,
`DIC` VARCHAR(12) NOT NULL,
`Misto_mo_id` INT NOT NULL,
PRIMARY KEY (`fir_id`),
PRIMARY KEY (`Misto_mo_id`),
FOREIGN KEY (`Misto_mo_id`) REFERENCES Firma(`Misto_mo_id`)
);
The tables `skoleni_has_termin' and 'skoleni_has_lektor' are most likely not needed here. I would bring dates to trainings table and leave just lektor_id in skoleni table as relation between trainings and lecturers is 1:n not m:n (unless one training can have more than one lecturer)