sql - 将子查询转换为自联接
问题描述
SQL 新手,我知道连接往往比子查询快。我有下表,我当前的查询为我提供了我需要的结果,但我无法围绕一个使用自联接的类似查询,假设它是可能的。
桌子
id scheduled_id action_id
------------ ------------ ------------
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 3 1
架构
create table ma (
id integer primary key,
scheduled_id integer,
action_id integer
);
insert into ma (
id,
scheduled_id,
action_id
)
values
(1, 1, 1),
(2, 1, 2),
(3, 1, 3),
(4, 2, 1),
(5, 2, 2),
(6, 3, 1);
询问
select * from ma where action_id = 3
union all
select * from ma where scheduled_id not in (
select scheduled_id from ma
where action_id = 3)
结果
id scheduled_id action_id
------------ ------------ ------------
3 1 3
4 2 1
5 2 2
6 3 1
我的结果应该是 action_id 值为 3 的所有行加上那些 schedule_id 的 action_id 值不为 3 的所有行。
可以在http://sqlfiddle.com/#!5/0ba51/3找到 sqlfiddle 。
谢谢你。
解决方案
SELECT m1.*
FROM ma m1
INNER JOIN
(
SELECT *
FROM ma m2
WHERE m2.action_id = 3
) AS matbl
WHERE m1.action_id = 3
OR matbl.scheduled_id<>m1.scheduled_id
希望它会有所帮助。
推荐阅读
- android - Flutter - Activity 类不存在
- c++ - 从 2 笔交易计算默克尔根
- android - Kotlin 流程,回调
- html - 环绕图标的底部对齐跨度
- flutter - Flutter First Letter Bloc Builder 无名称时出错
- sockets - 在服务器端执行命令
- directx-12 - 无法使用 D3D12 渲染三角形
- linux - PID 重用,边缘情况?
- php - 无法使用 laravel-websockets 通过 Echo 接收通知
- bert-language-model - 为什么 AllenNLP `PretrainedTransformerEmbedder` 输出所有 `last_hidden_state` 包括第一个 `[CLS]`?