sql - 从另一个表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.questions
。user_id
id
test.users
例如,如果我想删除id
10 from的行test.questions
(因为该行对应于john@site.com
in test.users
),我可以这样做
DELETE FROM test.questions WHERE answer = true AND user_id = 1
这将只删除带有id = 10
from的行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]
解决方案
一种方法使用子查询:
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';
推荐阅读
- oracle - 当我尝试在其上加入两个表时,我的触发器出现循环和大小写错误
- spring-boot - 全局 cors 配置在 Spring Boot 中不起作用,但 indivisual @CrossOrigins 工作
- docker - Jenkins 声明式管道,带有用于整个管道和某些阶段的单独 docker 映像
- php - 如何在不改变第二位小数(1.255 => 1.25)的情况下获得两位十进制数?
- c++ - STL 列表 在 Visual Studio 2013 中编译的代码在 Visual Studio 2019 中出现错误。想知道原因
- excel - 在 Excel 中使用 VBA 在与工作表不同的工作表上查找和更新相关记录
- javascript - 如何根据其父组件在屏幕上的位置移动Vuetify组件```VDatePicker```
- sql - 如何修复 SQL 语句中的 H2 语法错误?
- spring-amqp - 无论指定的并发性如何,如果队列非空但未接收消息,RabbitMQ 侦听器只会为每个消费者启动一个线程
- javascript - 选项 modal: true in magnificpopup 不起作用