MySQL:唯一的多列索引和NULL

时间:2016-09-23 14:41:00

标签: mysql

我有一个包含用户电子邮件地址(TINYTEXT)和商店位置的表(只是一个INT)。每个电子邮件地址在每个位置都应该是唯一的,因此允许:

test@example.com on location 1
test@example.com on location 2
test@example.com on location 3
but not:
test@example.com on location 1
test@example.com on location 1

所以我创建了一个索引:

UNIQUE KEY email_per_location(email, location)

到目前为止工作正常并且如果我添加已经存在的email-adrress-location-combination组合则会引发错误。

现在我想添加应该有权访问所有位置的用户。我不想为每个位置添加一个,所以想法是将位置设置为NULL,如下所示:

test@example.com on location 1 -> Has access to location 1 
test@example.com on location 2 -> Has access to location 2 
admin@example.com on location NULL -> Has access to ALL locations

我的索引问题:

UNIQUE KEY email_per_location(email, location)

是,这不会引发错误(但它应该):

admin@example.com on location 1 -> Has access to location 1 
admin@example.com on location NULL -> Has access to ALL locations

是否有可能创建一个不允许这种情况的索引(或其他?)?

补充:如果有一个很好的解决方案,可以使用另一个值"所有位置" (不是NULL值)这也没关系。

0 个答案:

没有答案
相关问题