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
Related
Im a beginner in mysql, i don't understand my mistake
its a problem with the foreign key of "membre" and "club".
CREATE TABLE club(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) UNIQUE NOT NULL,
INDEX club_nom_index (nom),
adresse_id INT NOT NULL,
nom_du_responsable VARCHAR(255) NULL,
FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);
CREATE TABLE membre(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
prénom VARCHAR(255) NOT NULL,
adresse_id INT NOT NULL,
club_id INT NOT NULL,
rang_qualification INT NOT NULL,
numéro_téléphone VARCHAR(255) NULL,
courriel VARCHAR(255) UNIQUE NULL,
INDEX membre_courriel_index (courriel),
nb_parties_gagnées INT NOT NULL,
nb_parties_perdues INT NOT NULL,
nb_parties_nulles INT NOT NULL,
FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),
INDEX nom_prénom_membre_index (nom, prénom),
CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);
CREATE TABLE tournoi(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
INDEX tournoi_nom_index (nom),
club_id INT NOT NULL,
date_début DATE NOT NULL,
date_fin DATE NOT NULL,
FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),
CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);
CREATE TABLE partie(
id INT PRIMARY KEY AUTO_INCREMENT,
membre1_id INT NOT NULL,
membre2_id INT NOT NULL,
résultat INT NULL,
date_début DATE NULL,
heure_début TIME NULL,
id_tournoi INT NOT NULL,
FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),
INDEX membres_index(membre1_id, membre2_id),
CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);
CREATE TABLE adresse(
id INT PRIMARY KEY AUTO_INCREMENT,
adresse VARCHAR(255) NOT NULL,
rue VARCHAR(255) NOT NULL,
ville VARCHAR(255) NOT NULL,
code_postal CHAR(6) NULL,
INDEX adresse_code_index (code_postal),
province_état CHAR(3) NULL,
pays CHAR(2) NOT NULL,
CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
[[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);
CREATE TABLE rang(
qualification INT PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(255) UNIQUE NULL
);
I was expecting the program to run but it keeps telling me that there is a problem with the foreign key in "membre" and "club".
You must change the order of the create statements.
First table rang and second table adresse, because the other tables have references to these tables:
CREATE TABLE rang(
qualification INT PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(255) UNIQUE NULL
);
CREATE TABLE adresse(
id INT PRIMARY KEY AUTO_INCREMENT,
adresse VARCHAR(255) NOT NULL,
rue VARCHAR(255) NOT NULL,
ville VARCHAR(255) NOT NULL,
code_postal CHAR(6) NULL,
INDEX adresse_code_index (code_postal),
province_état CHAR(3) NULL,
pays CHAR(2) NOT NULL,
CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
[[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);
CREATE TABLE club(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) UNIQUE NOT NULL,
INDEX club_nom_index (nom),
adresse_id INT NOT NULL,
nom_du_responsable VARCHAR(255) NULL,
FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);
CREATE TABLE membre(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
prénom VARCHAR(255) NOT NULL,
adresse_id INT NOT NULL,
club_id INT NOT NULL,
rang_qualification INT NOT NULL,
numéro_téléphone VARCHAR(255) NULL,
courriel VARCHAR(255) UNIQUE NULL,
INDEX membre_courriel_index (courriel),
nb_parties_gagnées INT NOT NULL,
nb_parties_perdues INT NOT NULL,
nb_parties_nulles INT NOT NULL,
FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),
INDEX nom_prénom_membre_index (nom, prénom),
CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);
CREATE TABLE tournoi(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
INDEX tournoi_nom_index (nom),
club_id INT NOT NULL,
date_début DATE NOT NULL,
date_fin DATE NOT NULL,
FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),
CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);
CREATE TABLE partie(
id INT PRIMARY KEY AUTO_INCREMENT,
membre1_id INT NOT NULL,
membre2_id INT NOT NULL,
résultat INT NULL,
date_début DATE NULL,
heure_début TIME NULL,
id_tournoi INT NOT NULL,
FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),
INDEX membres_index(membre1_id, membre2_id),
CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);
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;
I'm trying to create a software for a gym but I'm getting this error and I don't know why, I've trying for hours but nothing
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
PRIMARY KEY (IdSocio)
) ENGINE=INNODB;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
PRIMARY KEY (IdTipos)
) ENGINE = INNODB;
CREATE TABLE productos (
IdProducto INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Descripcion VARCHAR (100),
Costo_Individual DECIMAL(6,2) NOT NULL,
Precio_venta DECIMAL(6,2) NOT NULL,
Estado BOOL NOT NULL,
Cantidad_Inicial INT NOT NULL,
Cantidad_actual INT NOT NULL,
PRIMARY KEY(IdProducto)
) ENGINE = INNODB;
Error Code: 1215. Cannot add foreign key constraint
I'm getting this error for this tables
CREATE TABLE membresia(
IdMembresia INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Tipo VARCHAR(30) NOT NULL,
Fecha_Inicio DATE NOT NULL,
Fecha_Vencimiento DATE NOT NULL,
Inscripcion BOOL NOT NULL,
Estado_membresia VARCHAR(15) NOT NULL,
Fecha_modificacion DATE NOT NULL,
Total DECIMAL(6,2) NOT NULL,
Nota VARCHAR(100),
Fecha_Nota DATE,
PRIMARY KEY (IdMembresia),
CONSTRAINT IdSocio FOREIGN KEY (Nombre)
REFERENCES Socios (Nombre),
CONSTRAINT IdTipos FOREIGN KEY (Tipo,Total)
REFERENCES tipos (Tipo,Precio)
) ENGINE = INNODB;
CREATE TABLE ventas (
IdVenta INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Fecha_venta DATE NOT NULL,
cantidad INT NOT NULL,
Total DECIMAL(8,2),
Fecha_Modificacion DATE NOT NULL,
Nota VARCHAR (100),
PRIMARY KEY (IdVenta),
CONSTRAINT IdProducto FOREIGN KEY (Producto)
REFERENCES productos(Producto)
) ENGINE = INNODB;
This will get you over an initial hurdle. Though I doubt you really want an FK on a price but I don't know the translation into your mother tongue.
You need indexes on the referenced tables for the columns looked up in FK's.
create schema dbtest_xyz;
use dbtest_xyz;
-- drop table Socios;
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
PRIMARY KEY (IdSocio),
key(Nombre) -- ADDED *******************************
) ENGINE=INNODB;
-- drop table tipos;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
PRIMARY KEY (IdTipos),
key(Tipo), -- ADDED *******************************
key(Precio) -- ADDED *******************************
) ENGINE = INNODB;
-- drop table productos;
CREATE TABLE productos (
IdProducto INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Descripcion VARCHAR (100),
Costo_Individual DECIMAL(6,2) NOT NULL,
Precio_venta DECIMAL(6,2) NOT NULL,
Estado BOOL NOT NULL,
Cantidad_Inicial INT NOT NULL,
Cantidad_actual INT NOT NULL,
PRIMARY KEY(IdProducto),
key(Producto) -- ADDED *******************************
) ENGINE = INNODB;
CREATE TABLE membresia(
IdMembresia INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Tipo VARCHAR(30) NOT NULL,
Fecha_Inicio DATE NOT NULL,
Fecha_Vencimiento DATE NOT NULL,
Inscripcion BOOL NOT NULL,
Estado_membresia VARCHAR(15) NOT NULL,
Fecha_modificacion DATE NOT NULL,
Total DECIMAL(6,2) NOT NULL,
Nota VARCHAR(100),
Fecha_Nota DATE,
PRIMARY KEY (IdMembresia),
CONSTRAINT IdSocio FOREIGN KEY (Nombre)
REFERENCES Socios (Nombre),
CONSTRAINT IdTipos FOREIGN KEY (Tipo)
REFERENCES tipos (Tipo),
CONSTRAINT IdMembresia FOREIGN KEY (Total)
REFERENCES tipos (Precio)
) ENGINE = INNODB;
CREATE TABLE ventas (
IdVenta INT NOT NULL AUTO_INCREMENT,
Producto VARCHAR (40) NOT NULL,
Fecha_venta DATE NOT NULL,
cantidad INT NOT NULL,
Total DECIMAL(8,2),
Fecha_Modificacion DATE NOT NULL,
Nota VARCHAR (100),
PRIMARY KEY (IdVenta),
CONSTRAINT IdProducto FOREIGN KEY (Producto)
REFERENCES productos(Producto)
) ENGINE = INNODB;
-- Cleanup:
drop schema dbtest_xyz;
Mysql Manual Page on Foreign Keys
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Note, the reason I have the drop tables above some tables is that it is wise to have them in place while one iteratively attempts the creations. When the FK creations fail, one often (almost always) has to re-jigger the referenced and referencing tables.
Your first 2 tables should be as per below, means referenced fields should be indexed.
CREATE TABLE Socios (
IdSocio INT NOT NULL AUTO_INCREMENT,
Nombre VARCHAR(30) NOT NULL,
Apellido VARCHAR(30) NOT NULL,
N_Celular VARCHAR(12),
Correo VARCHAR(60),
Fecha_Nacimiento DATE NOT NULL,
Fecha_Asociacion DATE NOT NULL,
Fecha_Modificacion DATE NOT NULL,
Notas VARCHAR(100),
KEY idx_Nombre(Nombre),
PRIMARY KEY (IdSocio)
) ENGINE=INNODB;
CREATE TABLE tipos(
IdTipos INT NOT NULL AUTO_INCREMENT,
Tipo VARCHAR (30) NOT NULL,
Precio DECIMAL(6,2) NOT NULL,
KEY idx_tipo_precio(Tipo,Precio),
PRIMARY KEY (IdTipos)
) ENGINE = INNODB;
In case this may help someone else one day, I had this issue yet none of the existing solutions helped - columns were same type, same collation, etc.
However, I had a stored generated column in the table containing the foreign key that referenced that key column, and for some reason this broke the foreign key generation. Removing the generated column and using a trigger instead fixed it.
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
Where is the problem? i am trying to create the table comparein using the composed primary key from the table Episodi but there should be a problem that i can t see..
the primary key from the table is a combination of "numero" and "titolo_episodio"
create table Autori(
id_autore int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15) not null,
nome_arte varchar (15)
) ENGINE=InnoDB;
create table Serie(
nome varchar(25) primary key,
id_autore int(6),
descrizione varchar(400),
FOREIGN KEY (id_autore)REFERENCES Autori(id_autore)
) ENGINE=InnoDB;
create table Episodi(
titolo_episodio varchar(25) not null,
numero int not null,
durata time not null,
data_trasmissione date not null,
nome_serie varchar(25),
PRIMARY KEY(titolo_episodio,numero),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Personaggi(
id_pers int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15),
nazionalita varchar (15),
nome_serie varchar(25),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Utenti(
nickname varchar(15) primary key,
nazionalita varchar(15) not null,
mail varchar(25) not null,
pwd varchar(15) not null,
amministratore bool default 0 not null
) ENGINE=InnoDB;
create table Generi(
genere varchar(15) primary key
) ENGINE=InnoDB;
create table comparein(
id_pers int not null,
numero int not null,
titolo_episodio varchar(25),
FOREIGN KEY (id_pers)REFERENCES Personaggi(id_pers),
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio),
primary key(id_pers,numero,titolo_episodio)
) ENGINE=InnoDB;
I think you need to reference the PK columns in the same order as the primary key was defined. So instead of
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio)
use
FOREIGN KEY (titolo_episodio, numero) REFERENCES Episodi(titolo_episodio, numero)
SQLFiddle: http://sqlfiddle.com/#!2/363bd