Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when foreign referencing in mySQL (Error 3780)

I am making two tables and I want the personOne column from table b to reference the person column on table a, but for some reason it doesn't work.

I have the below code as an example:

create table a(
person varchar(20),
cost varchar(10) not Null
)character set latin1
collate latin1_general_ci;


create table b(
personOne varchar(20),
personTwo varChar(2) not null,
key person_index (personOne),
CONSTRAINT C FOREIGN KEY (personOne) references a(person)
) engine=InnoDB default charset=latin1;

It is telling me an error:

Error Code: 3780. Referencing column 'personOne' and referenced column 'person' in foreign key constraint 'C' are incompatible.

I tried to to set table a engine to InnoDB, but that didn't work. I researched the problem more but couldn't figure out how to fix it.

like image 578
user12271400 Avatar asked Oct 24 '19 23:10

user12271400


People also ask

What is error 3780 in MySQL?

Error Code: 3780. Referencing column 'personOne' and referenced column 'person' in foreign key constraint 'C' are incompatible.

How do I change the foreign key references for a table in MySQL?

Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!

What is error code 1072 in MySQL?

You're trying to define as FOREIGN KEY, a column which is not present on your query.


2 Answers

The two columns must have the same collation. I'm guessing your table b is using the default collation for old versions of MySQL, which is latin1_swedish_ci.

You might like to review this checklist for foreign keys: https://stackoverflow.com/a/4673775/20860

I suggest the best choice is to declare both a and b tables with character set utf8mb4 and collation utf8mb4_unicode_520_ci if your version of MySQL is new enough to support it.

like image 66
Bill Karwin Avatar answered Nov 07 '22 14:11

Bill Karwin


Here I had to first define a primary key in a:

ALTER TABLE a ADD PRIMARY KEY (person);

And pass the COLLATE value of a:

CREATE TABLE b (
...
)ENGINE=InnoDB 
    DEFAULT CHARSET=latin1 
    COLLATE latin1_general_ci;
like image 34
FURIUS Avatar answered Nov 07 '22 15:11

FURIUS