按 DISTINCT 列限制/偏移
我需要选择所有带有所有相关标签的帖子:
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。
现在它显然正在以这种方式工作,它正在跳过/限制记录的数量,但不是真正的帖子的数量......
I need to select all posts with all their related tags:
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
So i get something like this:
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
I know when selecting records this way it is possible to get number of records through COUNT(p.id)
for example, but i didn't discover how to set OFFSET
(how many records skip from the beginning) and LIMIT
(how many records return at all) according to unique post ID.
Now it's obviously working in the way, that it's skipping/limiting the number of records, but not the number of real posts...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确,您需要从偏移量 O 开始的 N 个帖子的所有“标签”行:
附录
这是一种使用以下方法来实现的方法:
DENSE_RANK
仅受帖子本身限制:If I understand you correctly, you want all "tag" rows for N posts starting at offset O:
Addendum
Here's one way to do it using
DENSE_RANK
to limit just by the posts themselves:我对 PostgreSQL 不太熟悉,但是(如果我正确理解你的问题)我认为
ROW_NUMBER()
是正确的起点。像这样的事情:这应该可以在 MS SQL 中解决问题,您可能需要调整语法。
I'm not very familiar with PostgreSQL, but (if I understand your question right) I think
ROW_NUMBER()
is the right place to start. Something like this:This should do the trick in MS SQL, you may need to adjust the syntax.