使用USING语句

时间:2018-03-07 23:15:23

标签: sql postgresql

这第一部分工作正常

SELECT
company_user.id,
company_user_company.company_id
FROM
company_user_company
RIGHT JOIN company_user
ON company_user_company.company_user_id = company_user.id
WHERE
company_user_company.company_id ISNULL;

我想删除从该语句返回的所有行。根据文档,我应该能够做到这一点:

DELETE FROM company_user USING company_user_company
WHERE company_user.id = company_user_company.company_user_id AND company_user_company.company_id ISNULL;

该语句运行时没有错误,但返回0行。

1 个答案:

答案 0 :(得分:0)

我建议您使用NOT EXISTS()代替加密LEFT/RIGHT JOIN ... WHERE ...IS NULL

SELECT *
FROM company_user cu
WHERE NOT EXISTS( 
        SELECT * FROM company_user_company cuc
        WHERE cu.id = cuc.company_user_id
        );

    -- If the above yields the correct rows to be deleted
    -- , you can delete them
    -- With *almost* the same query:
DELETE 
FROM company_user cu
WHERE NOT EXISTS(
        SELECT * FROM company_user_company cuc
        WHERE cu.id = cuc.company_user_id 
        );