如何过滤RETURNING *?

时间:2016-10-30 06:25:37

标签: postgresql insert-update postgresql-9.5 sql-returning

我有以下情况。我有一个表,我有一个IsDeleted标志,用于对记录进行“软删除”。我正在做一个UPSERT,我正在添加,修改和标记为删除了一些记录。我想从RETURNING语句中排除已标记为已删除的记录。我试图将WHERE tbltest_IsDeleted = 0附加到以下SQL的末尾,但它给出了错误:ERROR:语法错误在“WHERE”处或附近

如何在以下声明中过滤RETURNING *的结果?

INSERT INTO tbltest (
    tbltest_ID,
    tbltest_Name,
    tbltest_Description,
    tbltest_IsDeleted) 
VALUES 
(DEFAULT, 'new record','new record description', 0),
(4, 'modified record name','modified record description', 0),
(5, 'existing record name','existing record description', 1)
ON CONFLICT (tbltest_ID) DO UPDATE SET (
    tbltest_Name,
    tbltest_Description,
    tbltest_IsDeleted) = (
    excluded.tbltest_Name,
    excluded.tbltest_Description,
    excluded.tbltest_IsDeleted) RETURNING *;

1 个答案:

答案 0 :(得分:1)

解决了这个问题,这是我能够做到的:

WITH rows AS (
    INSERT INTO tbltest (
            tbltest_ID,
            tbltest_Name,
            tbltest_Description,
            tbltest_IsDeleted) 
    VALUES 
    (DEFAULT, 'new record','new record description', 0),
    (4, 'modified record name','modified record description', 0),
    (5, 'existing record name','existing record description', 1)
    ON CONFLICT (tbltest_ID) DO UPDATE SET (
            tbltest_Name,
            tbltest_Description,
            tbltest_IsDeleted) = (
            excluded.tbltest_Name,
            excluded.tbltest_Description,
            excluded.tbltest_IsDeleted) RETURNING *
)
SELECT * FROM rows WHERE rows.tbltest_IsDeleted = 0

希望这能节省一些时间; - )