将子查询转换为自我加入

问题描述 投票:2回答:6

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的所有行加上那些没有action_id值为3的scheduled_ids的所有行。

可以在http://sqlfiddle.com/#!5/0ba51/3找到sqlfiddle。

谢谢。

sql sqlite subquery self-join
6个回答
1
投票

您正在寻找使用自联接的结果是:

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
投票

我认为JOIN不是你真正需要的。我会使用以下查询,这避免了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
    )

当检查某些事物的存在(或缺失)时,带有相关子查询的NOT EXISTS通常是最相关和最有效的方法。


1
投票
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

希望它会有所帮助。


1
投票

这个怎么样?虽然不是自我加入,但比联盟更快

select * from ma
where action_id = 3 or scheduled_id not in (
    select scheduled_id from ma
    where action_id = 3
  )

0
投票

我的结果应该是值为3的所有scheduled_ids以及那些没有值为3的scheduled_ids的所有scheduled_ids和action_ids。

这不是您的查询所做的。执行此操作的查询是:

select ma.*
from ma
where exists (select 1
              from ma ma2
              where ma2.scheduled_id = ma.scheduled_id and
                    ma2.action_id = 3
             );

虽然您可以使用自联接执行此操作,但这很棘手,因为查询可能会导致重复。我推荐使用existsin作为逻辑。


0
投票

此代码仅在您的action_id始终为1,2,3,4等并且从不跳过3时才有效。我只想提供备用答案,以防添加max(action_id)概念对您有用。

select ma.id
     , ma.scheduled_id
     , ma.action_id
     , ma_max.max_action_id
from (
    select scheduled_id
         , max(action_id) as max_action_id
    from ma
    group by scheduled_id
) ma_max
join ma
    on ma_max.scheduled_id = ma.scheduled_id 
where (action_id = 3 or max_action_id < 3)

它几乎肯定不会像使用“EXISTS”的其他答案一样好。我只是喜欢逻辑的复杂性如何在where (action_id = 3 or max_action_id < 3)中减少到基本上一个易于阅读的行。

© www.soinside.com 2019 - 2024. All rights reserved.