简体   繁体   English

MYSQL - 外键 varchar 列

[英]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:我创建了languages表,我想将外键添加到用户表:

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:我无法在lang列上添加外键:

error code: 150 "Foreign key constraint is incorrectly formed"错误代码:150“外键约束形成不正确”

Why I can't create varchar foreign key.为什么我不能创建 varchar 外键。 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 .我不会在语言表中添加 int 主键,因为我想从数据库中获取数据作为/api/users/cs而不是/api/users?lang=1

Thanks谢谢

You didn't specify the character set or collation for the languages table.您没有为languages表指定字符集或排序规则。

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.尽管users明确为utf8 ,但您可能正在使用默认字符集为 utf8mb4 的 MySQL 版本或默认字符集为 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 .它必须与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:如果您将表languages的默认字符集更改为您为表users定义的utf8 ,那么它将起作用:

ALTER TABLE languages CONVERT TO CHARACTER SET utf8;

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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