7

mysql 表设计规范讨论

 3 years ago
source link: https://www.v2ex.com/t/782576
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  MySQL

mysql 表设计规范讨论

  brader · 7 小时 19 分钟前 · 1477 次点击
CREATE TABLE `test` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL DEFAULT 0,
  `name` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

有这样一张表,我知道的设计表规范其中一条就是字段尽量不要设为 null 。

现在这个表业务背景是这样的,会先录入数据,但是没有 user_id,user_id 是后续更新进去的,但是要保证 user_id 是唯一的。

如果不设置 user_id 为 null 的话,user_id 是没办法弄唯一键的。

那么这种背景下,有没有必要打破表设计规范约束?

我的想法:本场景可以打破字段不为 Null 的约束,把 user_id 设为 Null,这样从数据库层面设置唯一键,不仅安全,而且业务层,也能少一次查询,数据是否唯一。 我觉得规范不是绝对的,就好像我们某些表多几个字段做数据冗余,不也是打破三范式的吗?

你们的看法呢?

第 1 条附言  ·  6 小时 4 分钟前

我看到很多人让我用 user_id 做主键,这里对不起,是我贴出的表,省略了一些字段,造成了大家的误会。
是这样的,我这个表,是另外一张表,和 user 表是一对一关联关系来的,user_id 是逻辑外键来的,所以是不能作为主键和自增的。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK