2013-11-03 18 views
0

我的網站上有一個關注系統,您可以在其中跟蹤其他用戶。查詢使用其他表中的ID獲取最新的10行

在網站的主頁上,我試圖讓它顯示您正在關注的用戶的最新10條信息(而不是您關注的每個人的10條信息,但總共有10個)。

我有一臺名爲followers結構如下:

id | user_id | following_id 
1  20   52 
2  20   55 
1  20   75 
...  ...   ... 

哪裏user_id是你的ID和follow_id是您關注的用戶的ID。

然後我有一個名爲posts的表,其中收集了來自用戶的所有帖子。

我現在要做的是創建一個查詢,從您正在關注的用戶(按日期排序)獲取最新的10條信息。

這是我到目前爲止已經做出:

/* Select all users this person is following */ 
$stmt = $cxn->prepare('SELECT following_id FROM followers WHERE user_id = ?'); 
$stmt->bind_param('i', $user_id); 
$stmt->execute(); 
$result = $stmt->get_result(); 

/* If a result exists, continue. */ 
if ($result->num_rows) { 
    while ($row = $result->fetch_assoc()) { 
     // not sure what to do here, how would the query look? 
    } 
} else { 
    echo "You aren't following anyone!"; 
} 

我不知道什麼查詢會/應該是從你關注的人一共拿到了最新的帖子10。

請幫忙!

+0

相關:[SQL只選擇最高值在列行(http://stackoverflow.com/q/7745609/1037210) – Lion

回答

3

您現在處於正確的軌道上,但您的主要選擇依然是帖子,而不是追隨者 - 這些都是子查詢。你可能想要這樣的東西。

SELECT * FROM posts WHERE poster_id IN 
    (SELECT following_id FROM followers WHERE user_id = ?) 
ORDER BY posted_at DESC 
LIMIT 10 

您編寫的查詢仍然存在,但它已被查詢包圍以獲取實際的帖子。用posts_id和posting_at代替你在帖子表中稱呼他們的內容。

+0

謝謝,它的工作! :) – Burrows

0
SELECT * 
FROM posts p 
JOIN followers f 
ON p.author_id = f.following_id 
WHERE f.user_id = ? 
ORDER BY p.date DESC 
LIMIT 10; 
相關問題