SQL:LIMIT 在 DISTINCT 之前执行
我正在做一个自定义 WordPress 查询,我需要对结果进行分页。 出于测试目的,限制设置为 2。当有 4 个唯一结果时,WP 在第一页上仅显示 1 个结果,并且在结果总数中它会错过最后一个结果。
我猜问题出在这个查询的结果上:
SELECT DISTINCT*
FROM wp_posts
LEFT JOIN wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id )
WHERE wp_posts.post_status ='publish'
AND wp_posts.post_type ='directory_listing'
AND wp_term_relationships.term_taxonomy_id
IN ( 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82)
ORDERBY wp_posts.post_title ASC
LIMIT 0 , 2
当我直接在 MySQL 上执行这个查询时,它返回两个重复项,而不是前两个唯一结果。
我这样做的方式不对吗?如何解决这个问题?
I am doing a custom WordPress query and I need to have pagination on the results.
For testing purposes limit is set to 2. When there are 4 unique results WP displays only 1 result on the first page and in the total of the results it misses the last result.
I guess the problem is in the result of this query:
SELECT DISTINCT*
FROM wp_posts
LEFT JOIN wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id )
WHERE wp_posts.post_status ='publish'
AND wp_posts.post_type ='directory_listing'
AND wp_term_relationships.term_taxonomy_id
IN ( 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82)
ORDERBY wp_posts.post_title ASC
LIMIT 0 , 2
When I execute this directly on MySQL it returns two duplicates instead of the two first unique results.
Am I doing this the wrong way? How to solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LIMIT
总是(或者应该是,除非有 bug)总是在SELECT DISTINCT
之后执行。我的猜测是,您的查询不会显示精确的重复项,它仅显示重复的wp_posts
列,这些列在wp_term_relationships
表中具有超过 1 个相关行,这意味着它们有多个相关的分类法。我还猜想您只需要
wp_posts.*
列。尝试一下,这也可以摆脱DISTINCT
:如果您还想要
wp_term_relationships
表中的分类法或其他列,则必须使用JOIN< /code> 查询并
GROUP BY
wp_posts.id
:The
LIMIT
is (or should be, unless there is a bug) always executed afterSELECT DISTINCT
. My guess is that your query does NOT show exact duplicates, it's only showing duplicatewp_posts
columns that have more than 1 related rows in thewp_term_relationships
table, meaning they have more than one related taxonomies.I also guess that you only need the
wp_posts.*
columns. Try this which also gets rid of theDISTINCT
:If you also want the taxonomies or other columns from the
wp_term_relationships
table, you'd have to use yourJOIN
query andGROUP BY
thewp_posts.id
: