【问题标题】:perform delete or update on unique violation in postgres在 postgres 中对唯一违规执行删除或更新
【发布时间】:2011-01-10 17:40:24
【问题描述】:

关于 Unique_violation 异常如何更新或删除引发异常的行

表格代码和插入

create table test
(
id serial not null,
str character varying NOT NULL,
is_dup boolean DEFAULT false,
CONSTRAINT test_str_unq UNIQUE (str)
);

INSERT INTO test(str) VALUES ('apple'),('giant'),('company'),('ap*p*le');

功能

CREATE OR REPLACE FUNCTION rem_chars()
  RETURNS void AS
$BODY$

BEGIN
begin 
update test set str=replace(str,'*','');
EXCEPTION WHEN unique_violation THEN
--what to do here to delete the row which raised exception or
--to update the is_dup=true to that row 
end;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION rem_chars() OWNER TO postgres;

【问题讨论】:

  • 你想做什么?异常中的 DELETE 还是 UPDATE?
  • @ahwnn 任何人都可以更新或删除。我知道语法,但不知道如何使用 where 子句将其应用于特定行,或者是否有类似于 last_insert_id 的东西返回行的 id这引发了异常。
  • 你应该从一开始就在问题中有这样的解释。我认为您无法找出是哪一行导致了问题。

标签: postgresql unique sql-delete unique-constraint


【解决方案1】:

-- 这将显示所有潜在的键冲突

SELECT a.id, a.str, b.id , b.str
FROM test a, test b
WHERE a.str = replace(b.str,'*','')
AND a.id < b.id;

-- 这将删除它们

DELETE FROM test WHERE id IN (
  SELECT b.id
  FROM test a, test b
  WHERE a.str = replace(b.str,'*','')
  AND a.id < b.id
);

【讨论】:

    【解决方案2】:

    我认为唯一的解决方案是分两步进行:

    更新测试 SET str = 替换(str,'*','') WHERE str NOT IN (SELECT replace(str,'*','') FROM test); 更新测试 SET is_dup = true WHERE str IN (SELECT replace(str,'*','') FROM test);

    至少我想不出更有效的方法。

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2021-10-12
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多