首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将子查询转换为自连接

将子查询转换为自连接
EN

Stack Overflow用户
提问于 2019-02-14 20:13:22
回答 6查看 559关注 0票数 2

我知道联接比子查询更快。我有下表,当前的查询给出了我所需的结果,但假设可能的话,我不能把头转到类似的使用self的查询上。

表格

代码语言:javascript
复制
id           scheduled_id action_id
------------ ------------ ------------
1            1            1
2            1            2
3            1            3
4            2            1
5            2            2
6            3            1

模式

代码语言:javascript
复制
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);

查询

代码语言:javascript
复制
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)

结果

代码语言:javascript
复制
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可以找到这只琴。

谢谢。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2019-02-14 20:58:41

您希望使用的自连接结果是:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2019-02-14 20:26:13

我不认为你真正需要的是加入。我将使用以下查询,它避免了UNION:

代码语言:javascript
复制
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
    )

当涉及到检查某物是否存在(或不存在)时,不存在关联子查询通常是最相关和最有效的方法。

票数 1
EN

Stack Overflow用户

发布于 2019-02-14 20:56:33

这个怎么样?虽然不是自我加入而是比联合更快

代码语言:javascript
复制
select * from ma
where action_id = 3 or scheduled_id not in (
    select scheduled_id from ma
    where action_id = 3
  )
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54698368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档