繁体   English   中英

如何在SQL子查询中使用Union

[英]how to use Union In sql sub-query

select user_id,name, login,lastseen from users where user_id 
in((select friend_id from connections where user_id=1 and connection=1) 
union (select user_id from connections where friend_id=1 and connection=1))

我想做这样的工作,但此查询显示错误。 如果我独立运行此子查询而没有backets,则工作正常。 以及如何重写此查询以提高性能

使用UNION跳过IN ,而是执行EXISTS

select user_id, name, login, lastseen
from users u
where exists (select 1 from connections c
              where c.connection = 1
                and ((u.user_id = c.friend_id and c.user_id = 1) or
                     (c.user_id = u.user_id and c.friend_id = 1)))

卸下多余的支架

select user_id,name, login,lastseen 
from users 
where user_id 
in (
    select friend_id 
    from connections 
    where user_id=1 and connection=1

    union 

    select user_id 
    from connections 
    where friend_id=1 and connection=1
   )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM