2009-12-07 161 views
-1

我有三個表格(用戶,朋友,帖子)和兩個用戶(user1和user2)。MySQL:3表連接查詢?

當user1將user2添加爲朋友,則user1可以像在Facebook上一樣查看user2的帖子。但是隻有user1將user2添加爲朋友的日期之後的帖子。我的查詢是這樣的:

$sql = mysql_query("SELECT * FROM posts p JOIN friends f ON 
     p.currentuserid = f.friendid AND p.time >= f.friend_since OR 
     p.currentuserid='user1id' WHERE f.myid='user1id' 
     ORDER BY p.postid DESC LIMIT 20"); 

它工作的一路很好,但有一點問題..... !! 它顯示用戶2,用戶3(所有用戶USER1作爲朋友等)員額單時間,但表示user1的帖子多.......即

user2. hi 
user1. userssfsfsfsfsdf 
user1. userssfsfsfsfsdf 
user3. dddddddd 
user1. sdfsdsdfsdsfsf 
user1. sdfsdsdfsdsfsf 

,但我在數據庫是單一的入口/後爲什麼它正在發生........ !!

我該如何解決?

+1

有人可以分開這個查詢,並使其更清晰?在那裏添加一些新行,並刪除PHP語法,因爲這個問題與PHP無關。 – matpie 2010-01-07 23:05:34

回答

0

我不是SQL專家,但我認爲你的問題處於JOIN狀態。我無法看到你如何與帖子和朋友一起加入,並獲得你需要的結果。一位SQL專家可能知道這一點,但對我來說這太困難了。

如果我是你,我會下破問題2個部分:

  1. 選擇用戶自己的帖子

  2. 選擇用戶的朋友的帖子

例如,你可以通過使用2種不同的條件來做到這一點,並在一個子查詢中進行與朋友表的聯接(我還沒有測試過!):

select * 

from posts p 

where 

p.currentuserid = 'user1id' 

or 

p.postid in 

(
select p2.postid 
from posts p2 
join friend f on p2.currentuserid = f.friendid 
where p2.time >= f.friend_since and f.myid='user1id' 
) 

另一種方法是使用工會(也沒有測試..):

select * 

from posts p 

where 

p.currentuserid = 'user1id' 

union 

select p2.* 

from posts p2 

join friend f on p2.currentuserid = f.friendid 

where p2.time >= f.friend_since and f.myid='user1id' 
0

我認爲,最簡單的解決方法是使用GROUP BY語句列posts.userId刪除重複的條目。但是這並不是解決問題的最佳方式。

0

你得到所有user1的朋友的帖子的原因是你沒有排位其中朋友的帖子查詢應該返回。

WHERE子句前面添加一個f.friendid = 'user2id'(或任何列名稱)。

0

你真的應該知道模式是什麼樣子,所以我們不需要做太多的假設。我假設user的主鍵是id,並且friendsuserid以及friendid字段。我還假設posts.currentuserid是創建該帖子的用戶的ID。如果沒有,請用posts.userid或其他正確的字段替換它。

您的查詢無法正常工作的原因是您至少需要2個連接。創建查詢時,最簡單的方法是從您擁有的內容開始,按照您的要求進行操作,一次加入。以下是查詢以獲得特定用戶可以閱讀的帖子:

SELECT p.* 
FROM user u 
JOIN friends f ON u.id = f.userid 
JOIN posts p ON ((u.id = p.currentuserid) OR (f.friendid = p.currentuserid AND p.time >= f.friend_since)) 
WHERE u.id = ? 
ORDER BY p.postid DESC LIMIT 20 

第二次加入是肉的地方。它規定爲了閱讀帖子,它(a)必須由你書寫,或者(b)必須由你的朋友在你與他們交往後寫信。

如果您還想得到誰創造了貼的用戶名(假設user.name保存用戶名),你需要一個第三聯接:

SELECT pu.name as 'Posted By', p.* 
FROM user u 
JOIN friends f ON u.id = f.userid 
JOIN posts p ON ((u.id = p.currentuserid) OR (f.friendid = p.currentuserid AND p.time >= f.friend_since)) 
JOIN user pu ON p.currentuserid = pu.id 
WHERE u.id = ? 
ORDER BY p.postid DESC LIMIT 20