[英]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.