简体   繁体   中英

MYSQL - foreign key varchar column

I would like to add localization to my database. I created languages table and I would like to add foreign key to user table:

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(60) DEFAULT NULL,
  `registrationDate` datetime DEFAULT current_timestamp(),
  `lastLoginDate` datetime DEFAULT NULL,
  `isConfirmed` tinyint(1) NOT NULL DEFAULT 0,
  `activationKey` varchar(32) NOT NULL,
  `resendEmail` tinyint(1) DEFAULT NULL,
  `subscribedNews` tinyint(1) NOT NULL DEFAULT 1,
  `activated` tinyint(1) DEFAULT 1,
  `lang` varchar(5) NOT NULL DEFAULT 'en'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

create table languages(
    code varchar(5) primary key,
    name varchar(255) not null,
    dateFormat varchar(255),
    dateTimeFormat varchar(255),
    currency varchar(255)
);

ALTER TABLE users
ADD lang varchar(5) NOT NULL DEFAULT 'cs';

ALTER TABLE users ADD CONSTRAINT fk_user_lang FOREIGN KEY (lang) REFERENCES languages(code);

I can't add foreign key on lang column:

error code: 150 "Foreign key constraint is incorrectly formed"

Why I can't create varchar foreign key. I would not add int primary key in languages table, because, I would like to get data from database as /api/users/cs instead of /api/users?lang=1 .

Thanks

You didn't specify the character set or collation for the languages table.

Whereas users is explicitly utf8 , you might be using a MySQL version where the default charset is utf8mb4 or a very old version where the default charset is latin1.

Double-check with:

SHOW CREATE TABLE languages\G

That will display the charset and collation for that table. It must be the same as the charset and collation for the foreign key column in users .

If you change the default character set of the table languages to utf8 , which you defined for the table users , then it will work:

ALTER TABLE languages CONVERT TO CHARACTER SET utf8;

See the demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM