MySQL 中的条件组合键?
所以我有一个带有复合键的表,基本上“userID”-“data”必须是唯一的(请参阅我的其他问题SQL 表 - 半唯一行?)
但是,我想知道是否可以使其仅在 userID 不为零时才生效?我的意思是,“userID”-“data”对于非零 userID 必须是唯一的?
还是我找错了树?
谢谢
马拉
So I have this table with a composite key, basically 'userID'-'data' must be unique (see my other question SQL table - semi-unique row?)
However, I was wondering if it was possible to make this only come into effect when userID is not zero? By that I mean, 'userID'-'data' must be unique for non-zero userIDs?
Or am I barking up the wrong tree?
Thanks
Mala
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQL 约束适用于表中的每一行。您不能根据某些数据值将它们设置为有条件的。
但是,如果您可以使用 NULL 而不是零,则可以绕过唯一约束。唯一约束允许多个具有
NULL
的条目。原因是唯一性意味着不存在两个相等的值。相等意味着value1 = value2
必须为 true。但在 SQL 中,NULL = NULL
是未知,不是真的。到目前为止一切顺利,现在您可能认为以下语句会违反唯一约束,但事实并非如此:
SQL constraints apply to every row in the table. You can't make them conditional based on certain data values.
However, if you could use
NULL
instead of zero, you can get around the unique constraint. A unique constraint allows multiple entries that haveNULL
. The reason is that uniqueness means no two equal values can exist. Equality meansvalue1 = value2
must be true. But in SQL,NULL = NULL
is unknown, not true.So far so good, now you might think the following statements would violate the unique constraint, but they don't: