2009-12-06 24 views
0
使MySQL數據

如果我有兩個用戶一個用戶在交表的許多職位即爲不同的用戶

postid, post, userid, time(i.e timestamp) 

,我有另一個表的朋友,即

id, friendid, userid, friend_sinc(i.e timestamp) 

現在我想用戶朋友應該在他將user1添加爲朋友的日期之後看到user1的帖子。不是那些比他將他添加爲朋友的日期更早的帖子。我如何在單個MySQL查詢中完成它?

+0

我已經消毒了您的文字。句子以大寫字母開頭,並以一(1)個點結束。問題以問號「?」結尾。 'I'將被寫成大寫字母。如果你更認真地制定你的問題(即你付出更多努力),你會鼓勵其他人做出更多回應(即他們會付出更多的努力)。希望你能從中學習未來。另請參閱http://catb.org/esr/faqs/smart-questions.html – BalusC

回答

0

這將查找所有文章的人後,他們成爲了朋友與用戶12:

select  * 
from  Posts p 
join  Friends f 
on   p.userid = f.friendid 
and  p.time >= f.friend_since 
where  f.userid = 12 
+0

它給我以下問題,user12也無法看到自己的舊帖子,但可以看到較新的帖子....... ....!和其他問題是,如果用戶2有4個朋友和1個職位,它顯示了4次.....即1.職位1 2.職位1 3.職位1 – testkhan

0
SELECT p.* 
FROM post p, friend f 
WHERE p.userid = f.userid AND p.time >= f.friend_sinc; 

編輯:我想這可以解釋任何一種方式作爲persond ID是,但關鍵清楚了。

+0

它給我以下問題,user1也是無法看到它的舊帖子,但可以看到較新的帖子........... !!和其他問題是,如果用戶2有4個朋友和1個職位,它顯示了4次.....即 1.職位1 2.職位1 3.職位1 – testkhan

+0

你是在談論user1試圖看到它是自己的帖子?應該使用不同的查詢,因爲它試圖做不同的事情。 使用DISTINCT刪除重複項。 – unholysampler

0

隨着工會

select p.* from posts p where p.userid = <my_user_id> 
union 
select p.* from posts p, friends f where 
p.userid = f.friendid and 
f.userid = <my_user_id> and 
p.time >= f.friend_since 

或者你認爲自己是自己的朋友,那就是,有在friendfriendid = <my_user_id> and userid = <my_user_id> and friend_since = <date user was created>的條目,然後第二查詢工作,回到自己的崗位也是如此。我不認爲你會重複。

+0

它給我以下錯誤 ----------------------------------------- ------------------------- mysql_fetch_array():提供的參數不是有效的MySQL結果資源 ---------- -------------------------------------------------- ------ – testkhan

+0

查詢在概念上是可以的,但你需要使用p。*而不是*來使聯合工作。如果你不想要這個聯盟,可以使用我提到的技巧,也就是讓一個用戶成爲自己的朋友。 – ewernli

+0

你也可能想按日期訂購它們。如果你使用union,你將需要一個查詢,如「select u。* from(select p。* from ... union select p。* from ...)u order by u.time」。 – ewernli