【发布时间】:2019-02-14 20:13:22
【问题描述】:
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。
谢谢。
【问题讨论】:
-
您说 我的结果应该是所有值为 3...的 schedule_ids 但在您的查询中您有
select * from ma where action_id = 3。哪个是正确的? -
@forpas 我也对此感到困惑。鉴于结果表,我认为他们必须意味着他们想要任何具有 action_id = 3 的行以及具有 schedule_id 的所有行,其中 schedule_id 没有 action_id = 3 的行。(必须有更好的说法,但这是我现在能做的最好的了。)
-
对不起,你是对的;我已经更新了 OP。
标签: sql sqlite subquery self-join