gpt4 book ai didi

sql - 按 DISTINCT 列限制/偏移

转载 作者:太空狗 更新时间:2023-10-30 01:51:44 25 4
gpt4 key购买 nike

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

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

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

最佳答案

如果我没理解错的话,您希望 N 个帖子的所有“标签”行都从偏移量 O 开始:

   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}

关于sql - 按 DISTINCT 列限制/偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5921550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com