首页 > 解决方案 > 从另一个表postgresql的另一行中删除基于id的行

问题描述

在我的test.users桌子上,我有

id | email         | first_name
1  | john@site.com | John
2  | bob@site.com  | Bob

在我的test.questions桌子上,我有

id  | user_id | answer
10  | 1       | true
11  | 2       | false

我只想删除与一个特定用户匹配的行test.questionsuser_ididtest.users

例如,如果我想删除id10 from的行test.questions(因为该行对应于john@site.comin test.users),我可以这样做

DELETE FROM test.questions WHERE answer = true AND user_id = 1

这将只删除带有id = 10from的行test.questions,这是我想要的。

问题是我不想硬编码id. 我想在查询中仅对用户的电子邮件进行硬编码,并id动态获取。就像是

DELETE FROM test.questions WHERE answer = true AND user_id = [the id of john@site.com from test.users, which is 1]

标签: sqlpostgresql

解决方案


一种方法使用子查询:

DELETE FROM test.questions
    WHERE answer = true AND
          user_id = (SELECT u.id
                     FROM users u
                     WHERE u.email = 'john@site.com'
                    );

或者您可以使用USING

DELETE FROM test.questions q
    USING users u
    WHERE u.id = q.user_id AND
          u.email = 'john@site.com';

推荐阅读