Cannot add foreign key constraint 2 - mysql

im try create a foreign key to Poblacion, on table cp_cliente, but i cant, i take the error "cannot add foreign key", im try change the name, but i cant. If i delete Poblacion foreign key the script work fine.
CREATE TABLE provincias (
Cod_provincia INT(2) PRIMARY KEY,
Provincia VARCHAR(50) NOT NULL
);
CREATE TABLE cp_cliente (
CP CHAR(5),
Cod_provincia INT(2),
Poblacion VARCHAR(70),
PRIMARY KEY (CP, Poblacion, Cod_provincia),
FOREIGN KEY (Cod_provincia) REFERENCES provincias(Cod_provincia) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE cliente (
DNI CHAR(9) PRIMARY KEY,
Nombre VARCHAR(20) NOT NULL,
Apellidos VARCHAR(20) NOT NULL,
Direccion VARCHAR(50) NOT NULL,
CP CHAR(5),
Cod_provincia INT(2),
Poblacion VARCHAR(70),
FOREIGN KEY (CP) REFERENCES cp_cliente(CP) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (Cod_provincia) REFERENCES cp_cliente(Cod_provincia) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (Poblacion) REFERENCES cp_cliente(Poblacion) ON DELETE SET NULL ON UPDATE CASCADE
);
What is the problem? I can't see him :(
Sorry my bad english.

Related

Error on add foreign key constraint

Every time I'm trying to insert a foreign key to the table I got that message:
Error Code: 1215. Cannot add foreign key constraint 0.281 sec
My create table code:
CREATE TABLE `test`.`buy`(
`id` INT NOT NULL AUTO_INCREMENT,
`id_customer` INT UNSIGNED NOT NULL,
`code` VARCHAR(45) NOT NULL,
PRIMARY KEY(`id`),
UNIQUE INDEX `code_UNIQUE`(`code`),
CONSTRAINT `id_customer` FOREIGN KEY(`id_customer`) REFERENCES `test`.`customer`(`id_customer`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `code` FOREIGN KEY(`code`) REFERENCES `test`.`product`(`code`) ON DELETE RESTRICT ON UPDATE CASCADE
)
What should I do ?
Please format your code next time so it's easier to read.
You don't need the CONSTRAINT xxx bit, try this instead:
CREATE TABLE test.buy (
id INT NOT NULL AUTO_INCREMENT,
id_customer INT UNSIGNED NOT NULL,
code VARCHAR(45) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX code_UNIQUE (code),
FOREIGN KEY (id_customer)
REFERENCES test.customer (id_customer)
ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (code)
REFERENCES test.product (code)
ON DELETE RESTRICT ON UPDATE CASCADE
);
If that still doesn't work then make sure the other tables you reference (test.customer and test.product) already exist and that they have matching fields of the same data type.

Cannot add foreign keys constraint

CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
these are my tables I don't know why it displays "Cannot add foreign key constraint" please help
First create tblVoucher table then reference it in tblTransaction table
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
DEMO

MySQL ERROR 1215 (HY000): Cannot add foreign key constraint

I have looked everywhere about this error and seen plenty of examples and still i cant figure out whats wrong with my script. Im sorry if this is a common issue but searching about it hasnt helped me so far. Here goes the script:
CREATE DATABASE IF NOT EXISTS ventas;
USE ventas
CREATE TABLE TIENDAS (
nif varchar(10) not null,
nombre varchar(20),
direccion varchar(20),
poblacion varchar(20),
provincia varchar(20) check (provincia = upper(provincia)),
codpostal int(5),
PRIMARY KEY (nif)
) ENGINE=INNODB;
CREATE TABLE FABRICANTES (
cod_fabricante int(3) not null,
nombre varchar(15) check (nombre = upper(nombre)),
pais varchar(15) check (pais = upper(pais)),
PRIMARY KEY (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE ARTICULOS (
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
precio_venta int(4) unsigned CHECK (precio_venta > 0),
precio_costo int(4) unsigned CHECK (precio_costo > 0),
existencias int(5),
PRIMARY KEY (articulo,cod_fabricante,peso,categoria),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE PEDIDOS (
nif varchar(10) not null,
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
fecha_pedido date not null,
unidades_pedidas int(4),
PRIMARY KEY (nif,articulo,cod_fabricante,peso,categoria,fecha_pedido),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante),
FOREIGN KEY (articulo) references ARTICULOS (articulo) ON DELETE CASCADE,
FOREIGN KEY (cod_fabricante) references ARTICULOS (cod_fabricante) ON DELETE CASCADE,
FOREIGN KEY (peso) references ARTICULOS (peso) ON DELETE CASCADE,
FOREIGN KEY (categoria) references ARTICULOS (categoria) ON DELETE CASCADE,
FOREIGN KEY (nif) references TIENDAS (nif)
) ENGINE=INNODB;
Thanks a lot for your help.
In your ARTICULOS table, you have multiple columns as primary key .i.e. articulo,cod_fabricante,peso,categoria. In the PEDIDOS table, you are referring a foreign key articulo to ARTUCULOS table's articulo column. Which I think is wrong.
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns

multiple foreign keys cannot be added

I am wondering why i cannot be able to add this foreign keys.This is my schema
CREATE TABLE members(
member_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
num_1 int,
num_2 int,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (member_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE contacts(
contact_id INT NOT NULL AUTO_INCREMENT,
s1 int,
phone_number VARCHAR(10) NOT NULL,
s2 int,
s3 int,
PRIMARY KEY (contact_id),
FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8
I get this error on the mysql terminal
ERROR 1215 (HY000): Cannot add foreign key constraint
Is there a problem with my schema?.
Works for me this way:
CREATE TABLE members(
member_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
num_1 int,
num_2 int,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (member_id),
key idx_num1 (num_1),
key idx_num2 (num_2)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE contacts(
contact_id INT NOT NULL AUTO_INCREMENT,
s1 int,
phone_number VARCHAR(10) NOT NULL,
s2 int,
s3 int,
PRIMARY KEY (contact_id),
FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Just added
key idx_num1 (num_1),
key idx_num2 (num_2)
in table members. Foreign keys need to reference an indexed column (not necessarily unique and not necessarily NOT NULLable).
From the manual:
InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

#1005 - Can't create table 'classorganizer.turma' (errno: 150)

I keep getting the following error: *#1005 - Can't create table 'classorganizer.turma' (errno: 150) (Detalhes...) *
from trying to create the table Turma although I've double checked all the foreign keys cases in that class. Does anyone knows whats wrong?
Thank you!
CREATE TABLE Usuario(
email VARCHAR(50) NOT NULL,
nome VARCHAR(30),
senha INTEGER NOT NULL,
dataCadastro DATE NOT NULL,
CONSTRAINT pkUsu PRIMARY KEY(email),
CONSTRAINT formatoEmail CHECK(email LIKE '%#%.%')
)ENGINE=InnoDB;
CREATE TABLE Professor(
id INTEGER NOT NULL AUTO_INCREMENT,
nome VARCHAR(30) NOT NULL UNIQUE,
ranking INTEGER DEFAULT 3,
usuario VARCHAR(50) NOT NULL,
CONSTRAINT pk_prof PRIMARY KEY (id),
CONSTRAINT fk_usu FOREIGN KEY (usuario) REFERENCES Usuario(email) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT limites_rank CHECK(ranking >0 AND ranking<6)
)ENGINE=InnoDB;
CREATE TABLE Materia(
codigo VARCHAR(8) NOT NULL,
nro_turmas INTEGER DEFAULT 0,
nome VARCHAR(20) NOT NULL UNIQUE,
nro_cred_aula INTEGER DEFAULT 0,
nro_cred_trab INTEGER DEFAULT 0,
prioridade INTEGER DEFAULT 3,
usuario VARCHAR(50) NOT NULL,
CONSTRAINT pk_prof PRIMARY KEY (id),
CONSTRAINT fk_usu FOREIGN KEY (usuario) REFERENCES Usuario(email) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT limites_prio CHECK(prioridade >0 AND prioridade<6)
)ENGINE=InnoDB;
CREATE TABLE Turma(
nro INTEGER NOT NULL AUTO_INCREMENT,
prioridade INTEGER DEFAULT 3,
materia VARCHAR(8) NOT NULL,
professor INTEGER NOT NULL,
usuario VARCHAR(50) NOT NULL,
CONSTRAINT pk_turma PRIMARY KEY (nro),
CONSTRAINT fk_mat FOREIGN KEY (materia) REFERENCES Materia(codigo) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_prof FOREIGN KEY (professor) REFERENCES Professor(id) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT fk_usu FOREIGN KEY (usuario) REFERENCES Usuario(email) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT limites_prio CHECK(prioridade >0 AND prioridade<6)
)ENGINE=InnoDB;
There are lots of errors.
CONSTRAINT pk_prof PRIMARY KEY (id). id column doesn't exist in table Materia.
Constraint names (pk_prof, fk_usu) are already used in Professor table. You have used it in both Materia and Turma table.
Correct it by choosing unique names. Easiest way is to omit the name. MySQL handle it.
codigo column of Materia is referenced in Turma table, But its not a *key.*
professor column of Turma is defined to be NOT NULL. But you used ON DELETE SET NULL.