MySQL error code 1005 / errno: 150 - mysql

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;

Related

ERROR IN SQL COMMAND / FOREIGN KEY PROBLEM

I was training to create a table in SQL, but I got this message
The ideia of the code is this one:
/* criando as tabelas */
CREATE TABLE CLIENTES (
IDCLIENTE INT PRIMARY KEY AUTO_INCREMENT,
CLIENTE VARCHAR(10)NOT NULL,
ESTADO CHAR(2) NOT NULL,
SEXO ENUM ('M','F') NOT NULL,
STATUS VARCHAR (10)
);
CREATE TABLE VENDEDORES (
IDVENDEDOR INT PRIMARY KEY AUTO_INCREMENT,
NOME VARCHAR (20) NOT NULL
);
CREATE TABLE PRODUTOS (
IDPRODUTO INT PRIMARY KEY AUTO_INCREMENT,
PRODUTO VARCHAR (20) NOT NULL,
PRECO FLOAT(10,2) NOT NULL
);
CREATE TABLE VENDAS (
IDVENDA INT PRIMARY KEY AUTO_INCREMENT,
TOTAL INT NOT NULL,
ID_VENDEDOR INT ,
FOREIGN KEY (ID_VENDEDOR)
REFERENCES VENDEDORES(IDVENDEDOR)
ID_CLIENTE INT,
FOREIGN KEY (ID_CLIENTE)
REFERENCES CLIENTES(IDCLIENTE)
);
CREATE TABLE ITENS_VENDAS(
ID_VENDA INT NOT NULL,
ID_PRODUTO INT NOT NULL,
FOREIGN KEY ID_VENDA
REFERENCES VENDAS(IDVENDA)
FOREIGN KEY ID_PRODUTO
REFERENCES PRODUTOS(IDPRODUTO)
QUANTIDADE INT NOT NULL,
VALOR_UNITARIO FLOAT(10,2) NOT NULL,
VALOR_TOTAL FLOAT(10,2) NOT NULL,
DESCONTO FLOAT(10,2) NOT NULL
);
I was creating that from this idea of this flowchart:
I understand that I'm making a mistake in the foreign key part
but i can't understand what is wrong.
P.S: I'am new at programing in sql.
You have some syntax error
CREATE TABLE CLIENTES (
IDCLIENTE INT PRIMARY KEY AUTO_INCREMENT,
CLIENTE VARCHAR(10)NOT NULL,
ESTADO CHAR(2) NOT NULL,
SEXO ENUM ('M','F') NOT NULL,
STATUS VARCHAR (10)
);
✓
CREATE TABLE VENDEDORES (
IDVENDEDOR INT PRIMARY KEY AUTO_INCREMENT,
NOME VARCHAR (20) NOT NULL
);
✓
CREATE TABLE PRODUTOS (
IDPRODUTO INT PRIMARY KEY AUTO_INCREMENT,
PRODUTO VARCHAR (20) NOT NULL,
PRECO FLOAT(10,2) NOT NULL
);
✓
CREATE TABLE VENDAS (
IDVENDA INT PRIMARY KEY AUTO_INCREMENT,
TOTAL INT NOT NULL,
ID_VENDEDOR INT ,
FOREIGN KEY (ID_VENDEDOR)
REFERENCES VENDEDORES(IDVENDEDOR),
ID_CLIENTE INT,
FOREIGN KEY (ID_CLIENTE)
REFERENCES CLIENTES(IDCLIENTE)
);
✓
CREATE TABLE ITENS_VENDAS(
ID_VENDA INT NOT NULL,
ID_PRODUTO INT NOT NULL,
FOREIGN KEY (ID_VENDA)
REFERENCES VENDAS(IDVENDA),
FOREIGN KEY (ID_PRODUTO)
REFERENCES PRODUTOS(IDPRODUTO),
QUANTIDADE INT NOT NULL,
VALOR_UNITARIO FLOAT(10,2) NOT NULL,
VALOR_TOTAL FLOAT(10,2) NOT NULL,
DESCONTO FLOAT(10,2) NOT NULL
);
✓
db<>fiddle here

How to ER Diagram MYSQL

I'm trying to create simple library database in mysql. I have 5 tables students, entry, book, typebook, author. When I was trying to make er diagram with mysql reverse engineer my tables doesn't have any relationships on er diagram. But almost every databases have relationships on er diagram in the internet. What am i doing wrong and how to fix it?
CREATE TABLE student(
`stuNo` INT NOT NULL,
`stuname` VARCHAR(45) NULL,
`stusurname` VARCHAR(45) NULL,
`class` INT NULL,
`age` INT NULL,
PRIMARY KEY (`stuNo`));
CREATE TABLE entry(
`stuNo` INT NOT NULL,
`entryno` INT NOT NULL,
`bookno` INT NOT NULL,
`borrowdate` DATE NULL,
`returndate` DATE NULL,
PRIMARY KEY (`bookno`));
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (authorno , typeno));
CREATE TABLE typebook (
`typeno` INT NOT NULL,
`typename` VARCHAR(45) NULL,
PRIMARY KEY (`typeno`));
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`));
I had to switch the order of the CREATE TABLE
What changes is the order you have to insert data.
For example
If you want to INSERT a book , you first have to insert the typebook and author, that corresponds to the book and so on.
CREATE TABLE student(
`stuNo` INT NOT NULL,
`stuname` VARCHAR(45) NULL,
`stusurname` VARCHAR(45) NULL,
`class` INT NULL,
`age` INT NULL,
PRIMARY KEY (`stuNo`));
CREATE TABLE typebook (
`typeno` INT NOT NULL,
`typename` VARCHAR(45) NULL,
PRIMARY KEY (`typeno`));
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`));
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (authorno , typeno),
INDEX(bookno),
FOREIGN KEY (typeno)
REFERENCES typebook(typeno),
FOREIGN KEY (authorno)
REFERENCES author(authorno));
CREATE TABLE entry(
`stuNo` INT NOT NULL,
`entryno` INT NOT NULL,
`bookno` INT NOT NULL,
`borrowdate` DATE NULL,
`returndate` DATE NULL,
PRIMARY KEY (`bookno`),
FOREIGN KEY (stuNo)
REFERENCES student(stuNo),
FOREIGN KEY (bookno)
REFERENCES book(bookno)
);
Results in
The problem is that your tables do not have any FOREIGN KEYS set. MySQL has no idea that the authorno column from one table should be linked to the authorno column from another table. So no relationship links are generated.
To generate the relationship links to your ER diagram, you have to use FOREIGN KEY entries in your CREATE TABLE query to specify which column from one table is referencing a column from a different table:
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`)
);
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (bookno),
FOREIGN KEY (authorno) REFERENCES author(authorno)
);
With the added FOREIGN KEY entries MySQL now knows that the authorno column in book must reference a value from the authorno column of the author table. When generating the ER diagram you should get the lines between the tables to see the relationship.

SQL Management Studio - Database Diagram does not show every table created

So I have created a database which looks like that.
CREATE TABLE Budova
(
BudovaID int primary key not null,
BytyPocet int not null,
);
CREATE TABLE Skupina
(
SkupinaID int primary key not null,
NajemniciPocet int not null,
BytID int not null,
FOREIGN KEY (BytID) REFERENCES Byt(BytID) ON DELETE CASCADE,
);
CREATE TABLE Najemnici
(
NajemnikID int primary key not null,
Jmeno varchar(255) null,
Prijmeni varchar(255) null,
Vek int null,
SkupinaID int not null,
BytID int not null,
CenaEnergii int not null,
FOREIGN KEY (BytID) REFERENCES Byt(BytID),
FOREIGN KEY (SkupinaID) REFERENCES Skupina(SkupinaID)
);
CREATE TABLE Byt
(
BytID int primary key not null,
BudovaID int not null,
OpravaID int not null,
FOREIGN KEY (BudovaID) REFERENCES Budova(BudovaID) ON DELETE CASCADE,
FOREIGN KEY (OpravaID) REFERENCES Opravy(OpravaID) ON DELETE CASCADE
);
CREATE TABLE Vydaje
(
BytID int not null,
Voda int not null,
Elektrina int not null,
Plyn int not null,
Zaloha int not null,
Celkem int not null,
CelkemEura int not null
FOREIGN KEY (BytID) REFERENCES Byt(BytID)
);
CREATE TABLE Opravy
(
OpravaID int primary key not null,
OpravaTyp varchar(255) not null,
OpravaCena int not null,
);
I have basically 6 tables in the database but when I've tried to create database diagram, it haven't shown every single table.
As you can see, it shows only 5 of them.
At the end, it looks like that.
I've tried to change the references, but It went literally to hell. Do you know, what I should do to make it works?
You have a lot some errors on your statementm regardkless which dbms you use.
Try this create query in that order it is posted, or else the foreign keys won't work
CREATE TABLE Budova
(
BudovaID int primary key not null,
BytyPocet int not null
);
CREATE TABLE Opravy
(
OpravaID int primary key not null,
OpravaTyp varchar(255) not null,
OpravaCena int not null
);
CREATE TABLE Byt
(
BytID int primary key not null,
BudovaID int not null,
OpravaID int not null,
FOREIGN KEY (BudovaID) REFERENCES Budova(BudovaID) ON DELETE CASCADE,
FOREIGN KEY (OpravaID) REFERENCES Opravy(OpravaID) ON DELETE CASCADE
);
CREATE TABLE Skupina
(
SkupinaID int primary key not null,
NajemniciPocet int not null,
BytID int not null,
FOREIGN KEY (BytID) REFERENCES Byt(BytID) ON DELETE CASCADE
);
CREATE TABLE Najemnici
(
NajemnikID int primary key not null,
Jmeno varchar(255) null,
Prijmeni varchar(255) null,
Vek int null,
SkupinaID int not null,
BytID int not null,
CenaEnergii int not null,
FOREIGN KEY (BytID) REFERENCES Byt(BytID),
FOREIGN KEY (SkupinaID) REFERENCES Skupina(SkupinaID)
);
CREATE TABLE Vydaje
(
BytID int not null,
Voda int not null,
Elektrina int not null,
Plyn int not null,
Zaloha int not null,
Celkem int not null,
CelkemEura int not null,
FOREIGN KEY (BytID) REFERENCES Byt(BytID)
);

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

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.

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