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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值