我知道联接比子查询更快。我有下表,当前的查询给出了我所需的结果,但假设可能的话,我不能把头转到类似的使用self的查询上。
表格
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的所有行加上那些没有action_id值为3的scheduled_ids的所有行。
在http://sqlfiddle.com/#!5/0ba51/3可以找到这只琴。
谢谢。
发布于 2019-02-14 20:58:41
您希望使用的自连接结果是:
SELECT DISTINCT t1.*
FROM ma t1
JOIN ma t2
ON t1.SCHEDULED_ID <> t2.SCHEDULED_ID --Satisfies 2nd query
WHERE t2.ACTION_ID = 3 --Satisfies 2nd query
OR t1.ACTION_ID = 3 --Satisfies 1st query
ORDER BY t1.ID发布于 2019-02-14 20:26:13
我不认为你真正需要的是加入。我将使用以下查询,它避免了UNION:
SELECT m.*
FROM ma m
WHERE
m.action_id = 3
OR NOT EXISTS (
SELECT 1
FROM ma m1
WHERE
m1.scheduled_id = m.scheduled_id
AND m1.action_id = 3
)当涉及到检查某物是否存在(或不存在)时,不存在关联子查询通常是最相关和最有效的方法。
发布于 2019-02-14 20:56:33
这个怎么样?虽然不是自我加入而是比联合更快
select * from ma
where action_id = 3 or scheduled_id not in (
select scheduled_id from ma
where action_id = 3
)https://stackoverflow.com/questions/54698368
复制相似问题