2017-03-02 12 views
0
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)) 

私はこのような仕事をしていますが、このクエリはエラーを表示しています。私がこのサブクエリを独立して実行しても、バックセットなしで正常に動作しています。 ともどのように私はUnion in SQLサブクエリの使用方法

+0

何特にDBにタグをつけるください使っていますか。 –

答えて

1

は、UNIONINをスキップする代わりにEXISTSを行う

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 
    ) 
+0

本当に助けてくれてありがとう、ありがとう、ありがとう。 – user5921470

+0

正しい答えとしてマークplz –

2

余分な括弧を削除perforamanceを高めるために、このクエリを書き直すことができます。

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))) 
+0

これはなぜより良いと思うか説明することができますか? 私はその読みやすさを感じるので、その理由を理解したいと思います。 – NotCaring

+0

@カミル、私はそれが接続のテーブルを一度だけ、ユニオンのケースで2回の代わりに読むと思います。 (私たちはdbmsを知らないので、私は確かに言えません。) – jarlh

関連する問題