3

我正在创建查询以使用 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???
4

3 回答 3

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;

您还可以查看有关此的教程和有关此的讨论

干杯!:)

于 2010-05-03T04:25:33.420 回答
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;
于 2010-05-03T05:12:21.720 回答
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;
于 2010-05-03T05:27:13.417 回答