我創建查詢以使用SQL DB檢索論壇中的最新帖子。SQL檢索最新記錄,按唯一外鍵分組
我有一張名爲「Post」的表格。每篇文章與「線程」和「用戶」以及創建日期都有外鍵關係。
訣竅是我不想在同一個線程中顯示同一用戶或兩個帖子的兩篇文章。是否有可能創建一個包含所有這些邏輯的查詢?
# Grab the last 10 posts.
SELECT id, user_id, thread_id
FROM posts
ORDER BY created_at DESC
LIMIT 10;
# Grab the last 10 posts, max one post per user
SELECT id, user_id, thread_id
FROM post
GROUP BY user_id
ORDER BY date DESC
LIMIT 10;
# Grab the last 10 posts, max one post per user, max one post per thread???
也許我錯過了一些東西,但爲什麼會DISTINCT幫助?不是ID列的PK? – hgulyan 2010-05-03 04:43:13
DISTINCT不會幫助 - 因爲ID始終不同! – jbox 2010-05-03 05:04:32
我知道DISTINCT是解決方案的一部分,但不確定它的確切用途,所以還包括一個教程鏈接。 – DMin 2010-05-03 05:31:41