如何在删除后没有找到行的条件下更新/插入?

2023-12-23

我试图在删除不同表中的值后更新表。

这是我对这个问题的简化函数查询:

create function updateoutfit(_id uuid, _title text DEFAULT NULL::text, _garments json)
    returns TABLE(id uuid, title text, garments json)
    language sql
as
$$
WITH del AS (DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = _id RETURNING outfit_id),
     updateOutfit AS (
       UPDATE outfit SET
         title = _title
         FROM del
         WHERE outfit.id = _id
         RETURNING id, title
     ),
     saveOutfitGarment as (
       insert into outfit_garment (position_x, outfit_id)
         SELECT "positionX",
         (SELECT updateOutfit.id from updateOutfit)
         from json_to_recordset(_garments) as x("positionX" float,
                                                outfit_id uuid) RETURNING json_build_object('positionX', position_x) as garments)
SELECT id,
       title,
       json_agg(garments)
from updateOutfit as outfit,
     saveOutfitGarment as garments
group by id, title;
$$;

如果删除返回了outfit_id,效果很好:

DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = _id RETURNING outfit_id

但如果没有要删除的行,则会失败。我尝试过这样的事情:

DELETE FROM outfit_garment WHERE outfit_garment.outfit_id = '1234' RETURNING (SELECT '1234' as outfit_id );

但它仍然返回 0 行。

有没有办法解决这个问题或者更好的方法?

我正在使用 Postgres 13.2


If the DELETE找不到符合条件的行,其RETURNING子句返回no rows.

标题要求“删除后有条件更新/插入”,但身体却抱怨“如果没有要删除的行,则失败”。如果存在要删除的行不是条件,则条件是什么?

孤身一人出去,这might成为你想成为的人:

CREATE FUNCTION updateoutfit(_id UUID, _title text DEFAULT NULL::text, _garments json)
  RETURNS TABLE (id UUID, title text, garments json)
  LANGUAGE sql AS
$func$
DELETE FROM outfit_garment WHERE outfit_id = _id;  -- DELETE if exists

INSERT INTO outfit (id, title)  -- UPSERT outfit
VALUES (_id, _title)
ON CONFLICT (id) DO UPDATE
SET    title = EXCLUDED.title;
   
WITH ins AS (  -- INSERT new rows in outfit_garment
   INSERT INTO outfit_garment (position_x, outfit_id)
   SELECT "positionX", _id
   FROM   json_to_recordset(_garments) AS x("positionX" float)  -- outfit_id UUID was unused!
   RETURNING json_build_object('positionX', position_x) AS garments
   )
SELECT _id, _title, json_agg(garments)
FROM   ins
GROUP  BY id, title;
$func$;

它从表中删除所有行outfit_garment对于给定的 UUID,然后在表中插入或更新一行outfit,最后在表中添加新的详细信息行outfit_garment. Any outfit_id通过了_garments被忽略。
然后它返回一行,其中所有服装合并为一个 JSON 值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在删除后没有找到行的条件下更新/插入? 的相关文章

随机推荐