2017-03-02 18 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)) 

我想做一些這樣的工作,但這個查詢顯示錯誤。如果我獨立運行這個子查詢沒有backets它工作正常。 ,也是我怎麼可以重寫此查詢增加perforamance如何使用聯合在SQL中的子查詢

+0

請標記具體是什麼DB你正在用嗎。 –

回答

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

感謝隊友非常感謝你,真的幫助我 – user5921470

+0

標記爲正確的答案plz –

2

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

你能解釋爲什麼這會更好(我認爲更快,但看不出爲什麼)? 我覺得它不那麼可讀,所以想了解它爲什麼更好。 – NotCaring

+0

@Kamil,我想它只會讀取一次連接表,而不是在聯合情況下的兩次。 (因爲我們不知道dbms,我無法確定。) – jarlh