繁体   English   中英

如何将 UNIQUE 约束设置为多列 MySQL?

[英]How to set UNIQUE constraint to multiple columns MySQL?

我有一张桌子

table location_category {
    id,
    location_id,
    category_id,
    is_primary
}

我想要的是为组合 location_id 和 is_primary 设置一个 UNIQUE 约束。 我知道使用它会产生一个多列 UNIQUE 约束

ALTER TABLE `votes` ADD UNIQUE `unique_index`(`location_id`, `is_primary`);

但我担心的是,我们可以为一个位置设置多个类别,但只能将 1 个类别设置为主要类别。 例如:

| id | location_id | category_id | is_primary |
| 1  |      1      |      1      |      0     |
| 2  |      1      |      2      |      0     |
| 3  |      1      |      3      |      1     |
| 4  |      1      |      4      |      0     |

这会违反 UNIQUE 约束吗? 由于我有多个 location_id = 1 和 is_primary = 0 的实例?

只是想弄清楚这一点。 感谢您的帮助。

无需更改任何内容,UNIQUE 允许多个 NULL 值

CREATE TABLE `votes` ( `id` INTEGER, `location_id` INTEGER, `category_id` INTEGER, `is_primary` INTEGER ); ALTER TABLE `votes` ADD UNIQUE `unique_index`(`location_id`, `is_primary`); INSERT INTO `votes` (`id`, `location_id`, `category_id`, `is_primary`) VALUES ('1', '1', '1', NULL), ('2', '1', '2', NULL), ('3', '1', '3', '1'), ('4', '1', '4', NULL);
 SELECT * from `votes`
\n身份证 |  location_id |  category_id |  is_primary\n -: |  ----------: |  ----------: |  ---------:\n  1 |  1 |  1 | 空值\n  2 |  1 |  2 | 空值\n  3 |  1 |  3 |  1\n  4 |  1 |  4 | 空值\n

db<> 在这里摆弄

所以你只能有一个位置是主要的 1

暂无
暂无

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

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