SQL检索最新记录,按唯一外键分组

时间:2010-05-03 04:07:19

标签: sql mysql database duplicates greatest-n-per-group

我正在创建查询以使用SQL DB检索论坛中的最新帖子。

我有一张叫做“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???

3 个答案:

答案 0 :(得分:0)

试试这个,看看是否有帮助:

SELECT DISTINCT 
id, user_id, thread_id 
FROM posts 
ORDER BY created_at DESC LIMIT 10;

SELECT DISTINCT
id, user_id, thread_id
FROM post
GROUP BY user_id
ORDER BY date DESC
LIMIT 10;

您还可以看到关于此问题的tutorial 和关于此问题的discussion

干杯! :)

答案 1 :(得分:0)

我没有对此进行测试,但请尝试一下:

(
  SELECT p1.id, p1.user_id, p1.thread_id
  FROM post AS p1 LEFT OUTER JOIN post AS p2
    ON (p1.user_id = p2.user_id AND p1.date < p2.date)
  WHERE p2.id IS NULL
  ORDER BY p1.date DESC
  LIMIT 10
)
UNION DISTINCT
(
  SELECT p3.id, p3.user_id, p3.thread_id
  FROM post AS p3 LEFT OUTER JOIN post AS p4
    ON (p3.thread_id = p4.thread_id AND p3.date < p4.date)
  WHERE p4.id IS NULL
  ORDER BY p3.date DESC
  LIMIT 10
)
ORDER BY date DESC
LIMIT 10;

答案 2 :(得分:0)

这个怎么样?每个用户的第一个查询,每个用户和每个线程的第二个查询。

SELECT id, user_id, thread_id
FROM post p1
WHERE id = (SELECT id 
            FROM post 
            WHERE user_id = p1.user_id 
            ORDER BY date DESC 
            LIMIT 1) 
ORDER BY date DESC 
LIMIT 10;

SELECT id, user_id, thread_id
FROM post p1
WHERE id = (SELECT id 
            FROM post 
            WHERE user_id = p1.user_id 
            ORDER BY date DESC 
            LIMIT 1) 
AND id = (SELECT id 
          FROM post 
          WHERE thread_id = p1.thread_id 
          ORDER BY date DESC 
          LIMIT 1) 
ORDER BY date DESC 
LIMIT 10;