2014-02-07 96 views
-1

我有一個查詢,我正在使用來加入兩個表(帖子,關係),以從您正在關注的用戶(r.status = 1)或朋友(r.status = 2)返回帖子。但是,也可以省略帖子隱私私密(p.privacy = 2)和當前關係(r.status = 1)的帖子。使用兩個組合的MySQL查詢

這裏是我的查詢:

$user_id= 1; 

$posts_query= " 
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type 
FROM posts p 
JOIN relations r ON p.user_id = r.recipient 
AND (r.sender = '".$user_id."') 
AND NOT (r.status = 1 AND p.privacy = 2) 
ORDER BY p.post_id DESC; 
"; 

現在有了這個查詢的唯一問題是,它省略了自己的個人的帖子。

該查詢將是:

$your_posts_query= "SELECT * FROM posts WHERE user_id= '".$user_id."' ORDER BY p.post_id  
DESC"; 

現在,這並不讓我聚集所有的職位在一起。你的,以及你的朋友和你所關注的人。

我該如何使它成爲我的第一個查詢還包含我的第二個查詢所做的事情?

+2

AND(r.sender = ' 「$ user_ID的。」' OR p.user_id = ' 「$ user_ID的。」' ) –

+0

這不會因爲AND NOT(r.status = 1 AND p.privacy = 2)而無法工作 – user3259283

+0

您是否可以在sqlfiddle中發佈表結構和一些數據,以便在嘗試任何事情之前更明顯地看到它? –

回答

0
$user_id= 1; 

$posts_query= " 
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type 
FROM posts p 
JOIN relations r ON p.user_id = r.recipient 
AND (r.sender = '".$user_id."' OR p.user_id= '".$user_id."') 
AND NOT (r.status = 1 AND p.privacy = 2) 
ORDER BY p.post_id DESC; 
"; 
0

將二者結合起來,共同爲獲得一個結果集

$posts_query= " 
SELECT post_id, user_id, story, photo, link, collection_id, privacy, date, type 
FROM posts WHERE user_id= '".$user_id."' 
union 
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type 
FROM posts p 
JOIN relations r ON p.user_id = r.recipient 
AND (r.sender = '".$user_id."') 
AND NOT (r.status = 1 AND p.privacy = 2) 
ORDER BY p.post_id DESC; 
";