2017-07-03 84 views
3

我的表叫posts,我想retrieve所有滿足在select statement以下條件records,並返回一個single table -替代/替代工會與單個連接Select語句

select ID from posts where UserID= 23487 and postlevel <> 1 
select ID from posts where ParentID in (select ID from posts where UserID= 23487 and postlevel <> 1) 

現在,使用操作者UNION象下面我可以返回單個表 -

select ID from posts where UserID= 23487 and postlevel <> 1 
UNION 
select ID from posts where ParentID in (select ID from posts where UserID= 23487 and postlevel <> 1) 

輸出

enter image description here

嘗試以下JOIN查詢,但並沒有得到預期的結果,並返回NULL -

select ID from posts cs 
LEFT JOIN posts cs1 ON cs.ID = cs1.ID 
where cs.UserID = 23487 and cs.PostLevel <>1 and cs.ParentID = cs1.ID 

預計

我想獲取使用JOIN或使用單記錄SELECT而不是UNION以獲得如上所示的所需輸出。

+0

'Union'和'Join'是兩個不同的東西..爲什麼要用'Join'來做到這一點?如果你想尋求優化 –

回答

4

你有沒有嘗試過或運算在一起,這兩個條件中的一個WHERE條款:

select ID 
from posts 
where 
    (UserID = 23487 and postlevel <> 1) or 
    (ParentID in (select ID from cs_posts where UserID= 23487 and postlevel <> 1)) 
+0

返回25行,應該返回27 – PPB

+0

'UNION ALL'保留了重複數據,這種連接方式不會產生這種重複數據。如果你的'UNION'查詢工作正常,那麼爲什麼不使用它呢? –

+0

是的,對! 'UNION ALL'返回重複記錄,謝謝!標記爲解決方案 – PPB

1

你可以試試這個

select ID 
from posts 
where 
    (UserID = 23487 and postlevel <> 1) or 
    (EXISTS (select 1 from cs_posts where UserID= 23487 and postlevel <> 1 and ID = ParentID)) 
+0

只返回24行,根據聯合查詢應返回27 – PPB

0

沒必要工會或存在或....試試這個:

select distinct F1.id from post F1 inner join 
posts f2 on f2.UserID= 23487 and f2.postlevel <> 1 AND 
(F1.id=f2.id or F1.parentid=f2.id) 

如果你想保留重複值刪除不同的