首页 > 解决方案 > 将子查询转换为自联接

问题描述

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 。

谢谢你。

标签: sqlsqlitesubqueryself-join

解决方案


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

希望它会有所帮助。


推荐阅读