DISTINCT列的LIMIT / OFFSET

时间:2011-05-07 14:03:26

标签: sql database postgresql

我需要选择包含所有相关标签的所有帖子:

SELECT p.*, pt.name AS tag_name, pt.id AS tag_id FROM posts p
LEFT JOIN posts_tags pt ON pt.post_id = p.id

所以我得到这样的东西:

 p.id | p.name | p.content | tag_name | tag_id
  1   | Yahoo  | ...       | first    | 1
  1   | Yahoo  | ...       | second   | 2
  2   | Google | ...       | second   | 2
  2   | Google | ...       | third    | 3

我知道以这种方式选择记录时,可以通过COUNT(p.id)获取记录数量,但我没有发现如何设置OFFSET(从一开始就跳过多少条记录)和LIMIT(根据唯一的帖子ID

现在显然是在工作,它正在跳过/限制记录的数量,而不是真实帖子的数量......

2 个答案:

答案 0 :(得分:3)

如果我理解正确,您希望从 O 开始的 N 帖子的所有“标记”行:

   SELECT p.*, pt.name AS tag_name, pt.id AS tag_id
     FROM (SELECT * FROM posts ORDER BY id ASC LIMIT {N} OFFSET {O}) p
LEFT JOIN posts_tags pt
          ON pt.post_id = p.id

<强>附录

这是使用DENSE_RANK来限制帖子本身的一种方法:

   SELECT p.id, p.name, p.content, pt.name as tag_name, pt.id AS tag_id
     FROM (SELECT DENSE_RANK() OVER (ORDER BY id) AS dr, posts.*
             FROM posts) p
LEFT JOIN posts_tags pt
          ON pt.post_id = p.id
    WHERE dr BETWEEN {N} AND {N + O}

答案 1 :(得分:2)

我对PostgreSQL不是很熟悉,但是(如果我理解你的问题的话),我认为ROW_NUMBER()是正确的开始。像这样:

SELECT
  Tag_Name, Tag_ID
FROM
  (
  SELECT P.ID, P.Name AS Tag_Name, P.Content, ROW_NUMBER() OVER (ORDER BY P.ID, PT.Tag_ID) AS RowNum
  FROM Posts AS P LEFT JOIN Posts_Tags AS PT ON P.Post_ID = P.ID
  ) AS X
WHERE
  RowNum BETWEEN 101 AND 200

这应该可以解决MS SQL中的问题,您可能需要调整语法。