使用产生两列的子查询删除(在Postgresql中)

时间:2019-05-17 16:50:19

标签: sql postgresql subquery sql-delete

我必须删除一些与用子查询计算的两列匹配的记录。

我可以通过此查询正确看到它们:

let paramsSuccessFeedbackRoleArn = {
    TopicArn: topicArn,
    AttributeName: "LambdaSuccessFeedbackRoleArn",
    AttributeValue: "replace with arn for SuccessFeedbackRoleArn"
};
let paramsFailureFeedbackRoleArn = {
    TopicArn: topicArn,
    AttributeName: "LambdaFailureFeedbackRoleArn",
    AttributeValue: "replace with arn for FailureFeedbackRoleArn"
};
let paramsSuccessFeedbackSampleRate = {
    TopicArn: topicArn,
    AttributeName: "LambdaSuccessFeedbackSampleRate",
    AttributeValue: 0
};

这有效,我看到要删除的7个作业。

但是,删除并不像通过DELETE更改SELECT一样容易。

如果我这样做:

select * from user_assignments as ua, 
    (
        select user_assignments.user_id as uid, 
               job_selection as jid 
        from user_assignments
            join job_selections on job_id = jobs.id
            join data on job_selections.data_id = data.id
            where data.my_column IS NULL
    ) as sq
    where sq.uid = ua.user_id AND ua.job_selection_id = sq.jid;

我得到:

delete from user_assignments as ua, 
    (
        ...
    ) as sq
    where sq.uid = ua.user_id AND sq.jid = ua.job_selection_id;

我尝试了各种各样的组合,但是我无法使用。我想它一定很简单,但是我在SQL中是个新手。

基本上,我有一个子查询,该查询正确地产生了两列,可用于ERROR: syntax error at or near "," ,现在我想SELECT FROM user_assignments记录我知道可以选择的记录。

任何提示将不胜感激。预先谢谢你。

2 个答案:

答案 0 :(得分:1)

使用inexists

delete from user_assignments ua
where exists (select 1
              from user_assignments ua2 join
                   job_selections js
                   on ua2.job_id = js.id join
                   data d
                   on js.data_id = d.id
              where d.my_column IS NULL and
                    ua.user_id = sq.uid and ua.job_selection_id = sq.jid
             );

答案 1 :(得分:0)

哦,我明白了。

本教程this tutorial的特别之处, SQL部分使用具有别名的子查询删除记录

如果其他人感兴趣,我所做的就是:

DELETE FROM user_assignments ua
WHERE EXISTS(
    SELECT user_assignments.user_id as uid,
           user_assignments.job_selection as jid
    FROM user_assignments
        join job_selections on job_id = jobs.id
        join data on job_selections.data_id = data.id
    WHERE data.my_column IS NULL
        AND ua.user_id = uid
        AND ua.job_selection = jid
)

此查询在SELECT * FROM user_assignments上也可以正常使用