我正在创建查询以使用 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???
最佳答案
试试这个,看看是否有帮助:
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对这个。
干杯! :)
关于SQL检索最新记录,按唯一外键分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2756049/