我按照ID选择照片,然后按照订单字段选择下一张照片。
我检查照片id = 33的存在并按顺序查找下一张照片
SELECT `id` FROM `product_photo`
WHERE
`product_id` = (SELECT `product_id` FROM `product_photo` WHERE `id` = '33' )
AND
`order` >= (SELECT `order` FROM `product_photo` WHERE `id` = '33' )
LIMIT 2
是否可以简化此查询?
答案 0 :(得分:2)
有没有听说过JOIN
ing tables?
SELECT photo.id
FROM product_photo
INNER JOIN product_photo AS photo ON photo.product_id = product_photo.product_id
AND photo.order >= product_photo.order
WHERE product_photo.id = '33';
FROM
和WHERE
部分将选择您的产品id = 33
然后您加入product_photo
使用不同的别名(是的,您可以多次加入同一个表格)查询)基于product_id
和order
。