K
K
Konstantin Malyarov2016-06-20 23:29:10
MySQL
Konstantin Malyarov, 2016-06-20 23:29:10

Why is the foreign key not being set?

I wanted to link two tables ROLE and USERS.
Table data:

Table: role
Columns:
id_role int(11) AI PK 
role varchar(45)

Table: users
Columns:
id_user int(11) AI PK 
username varchar(45) 
password varchar(45) 
role int(11) PK 
department int(11) PK

When querying, an error pops up:
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1215: Cannot add foreign key constraint

Executing:
ALTER TABLE `moysclad`.`role` 
ADD CONSTRAINT `id`
  FOREIGN KEY (`id_role`)
  REFERENCES `moysclad`.`users` (`role`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Operation failed: There was an error while applying the SQL script to the database.
ERROR 1215: Cannot add foreign key constraint
SQL Statement:
ALTER TABLE `moysclad`.`role` 
ADD CONSTRAINT `id`
  FOREIGN KEY (`id_role`)
  REFERENCES `moysclad`.`users` (`role`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Karetnikov, 2016-06-21
@art_karetnikov

Why Primary key is on both fields? The Users table does not need this, a regular int and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question