在冲突上如何努力两个或多个约束?
我有一个表:
我想从另一个表中获取插入或更新数据。我的约束是三个字段:ID_1,ID_2和日期。它的字段必须在一起是唯一的。 如果我这样做:
ALTER TABLE my_table
ADD CONSTRAINT constr_1 UNIQUE (id_1, id_2, date);
然后:
insert into my_table
(id_1, id_2, quantity, date)
values (1, null, 5, '2022-04-27'), -- values I get another select request
(null, 5, 5, '2022-04-27'), -- this means that the values can be different
(99, 85, 100, '2022-04-29')
ON CONFLICT (id_1, id_2, date)
DO Update
SET quantity = excluded.quantity
约束不起作用,我只是插入具有相同值的新行。如何在没有记录和更新的情况下插入?
I have a table:
I want insert or update data, that I get from another table. My constrains are three fields: id_1, id_2 and date. It's fields must be unique together.
If I do:
ALTER TABLE my_table
ADD CONSTRAINT constr_1 UNIQUE (id_1, id_2, date);
and then:
insert into my_table
(id_1, id_2, quantity, date)
values (1, null, 5, '2022-04-27'), -- values I get another select request
(null, 5, 5, '2022-04-27'), -- this means that the values can be different
(99, 85, 100, '2022-04-29')
ON CONFLICT (id_1, id_2, date)
DO Update
SET quantity = excluded.quantity
Constrains not work and I just insert new rows with the same values. How to insert in the absence of a record and update in its presence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PostgreSQL将零视为独特的值,因此,您可以在具有唯一索引的列中具有多个空值。当您为表定义主键或唯一约束时,PostgreSQL会自动创建相应的唯一索引。
解决方案是与Colesce创建一个独特的索引。在此示例中,我使用了
cocce(〜,0)
,这意味着Null和0被视为同一件事。您可能更喜欢使用另一个值,例如int的最大可能值,即2147483648。请不要修改冲突列表以匹配索引。3行影响
1行影响
*db< EC5F)
PostgreSQL treats NULL as distinct value, therefore, you can have multiple NULL values in a column with a UNIQUE index. When you define a primary key or a unique constraint for a table, PostgreSQL automatically creates a corresponding UNIQUE index.
The solution is to create a unique index, with coalesce. In this example I have used
coalesce(~, 0)
which means that null and 0 are treated as the same thing. You might prefer to use another value, for example the maximum possible value of int which is 2147483648.Please not that we have to modify the ON CONFLICT list to match the index.3 rows affected
1 rows affected
*db<>fiddle here74bf159a4d041c31fec5f)
然后,
请检查手册部分: 5.4.3。独特的约束关于特殊情况: null 。
then
please check manual section: 5.4.3. Unique Constraints about special case: null.