我是靠谱客的博主 阔达绿茶,最近开发中收集的这篇文章主要介绍mysql查询带limit_MySQL选择带有子查询和LIMIT,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

bd96500e110b49cbb3cd949968f18be7.png

I am using the subselect to get the row IDs I need like this:

SELECT

p.id, c.id as category_id

FROM

(SELECT id FROM products p WHERE p.id > 6319055 ORDER BY id LIMIT 1000) prods

LEFT JOIN

products p ON p.id = prods.id

LEFT JOIN

categories c ON (c.id = p.category_id)

WHERE

c.active = 1

The ID 6319055 is my last selected ID. I save it after selecting the data.

Now the problem I am having is that I am selecting 1000 rows on each cycle and at some point I select 1000 rows which doesn't meet the

WHERE c.active = 1

requirements. Select returns nothing and I don't have any row ID to continue the subselect.

Any ideas how could I solve this? How can I get the last ID of the sub select, even if it doesn't meet the WHERE clause?

解决方案

When you use WHERE condition on the right-side table of a LEFT JOIN (Outer Join), it effectively becomes an INNER JOIN, because WHERE clause needs to match the conditions. That is why you are only getting cases where c.active = 1.

You need to shift the WHERE condition to LEFT JOIN .. ON .. AND .. condition:

SELECT

p.id, c.id as category_id

FROM

(SELECT id FROM products p WHERE p.id > 6319055 ORDER BY id LIMIT 1000) prods

LEFT JOIN

products p ON p.id = prods.id

LEFT JOIN

categories c ON c.id = p.category_id

AND c.active = 1

最后

以上就是阔达绿茶为你收集整理的mysql查询带limit_MySQL选择带有子查询和LIMIT的全部内容,希望文章能够帮你解决mysql查询带limit_MySQL选择带有子查询和LIMIT所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部