我有一张奖品代码表
codes
code, user_id, prize_id
我在user_id上有一个唯一索引,prize_id
所有代码都已在表格中,当用户兑换代码时,会分配一个user_id = NULL的随机代码。
不幸的是,这不起作用,因为唯一索引不允许我多次添加相同的prize_id而不指定user_id。
有没有办法告诉唯一索引不应该将NULL视为重复?
初始状态:
code, user_id, prize_id
A, NULL, 1
B, NULL, 1
C, NULL, 1
D, NULL, 2
E, NULL, 2
用户1兑换奖品2的代码后:
code, user_id, prize_id
A, NULL, 1
B, NULL, 1
C, NULL, 1
D, 1, 2
E, NULL, 2
答案 0 :(得分:1)
只需使用过滤后的索引:
create unique index unq_codes_user_prize on codes(user_id, prize_id)
where user_id is not null;