空值不是唯一的
我在 postgres 上有这样的行:
name | address | college
john | rome |
john | rome |
max | tokyo |
我创建了一个这样的表:
create test (
name varchar(10),
address varchar(20),
college varchar(20),
constraint test_uq unique (name,address,college);
如何使空值变得唯一,所以输出可以是这样的:
name | address | college
john | rome |
max | tokyo |
I have rows like these on postgres:
name | address | college
john | rome |
john | rome |
max | tokyo |
I create a table like this:
create test (
name varchar(10),
address varchar(20),
college varchar(20),
constraint test_uq unique (name,address,college);
How can I make null values become unique, so the output can be like this:
name | address | college
john | rome |
max | tokyo |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Postgres 文档声明此行为符合 SQL 标准:
一种可能性是重新考虑您的架构(说实话,对
name+address+college
的唯一性约束在您的示例中没有多大意义)。Postgres documentation claims that this behaviour is compliant with the SQL standard:
One possibility is to rethink your schema (to be honest, a uniqueness constraint on
name+address+college
doesn't make a whole lots of sense in your example).如果您只需要查询结果中的唯一记录,请使用
SELECT DISTINCT
如果您想强制执行唯一记录忽略空值,则必须创建一个条件唯一索引
HTH
If you just need unique records in the query result use
SELECT DISTINCT
If you want to enforce unique records ignoring null values you must create a conditional unique index
HTH
NULL 是未知的,因此 NULL 值永远不可能等于 NULL。要解决该法律,请执行以下操作。
为您的大学创建一个新的查找表。该表中有一条值为 None 的记录。然后将外键放入新的大学查找表中。
这是伪代码,因此您可能必须对其进行修改才能使其正常工作,但这是基本思想。
NULL is unknown so a value of NULL being equal to NULL can never be true. To work around this law do this.
Create a new look-up table for your colleges. In that table have a record with the value None. Then put a Foreign Key to the new college look-up table.
This is pseudo code so you may have to mess with it to make it work, but here is the basic idea.
如果将其设为主键,而不是唯一约束,它就会起作用。为此,
college
列必须为NOT NULL
并使用(例如)空字符串而不是 NULL 值。或者您正在寻找查询?
If you make it a primary key, instead of a unique constraint, it would work. For that, the column
college
would have to beNOT NULL
and use (for instance) empty strings instead of NULL values.Or are you looking for a query?