如何最小化这个mysql查询

时间:2013-09-20 06:30:11

标签: mysql sql

我按照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

是否可以简化此查询?

1 个答案:

答案 0 :(得分:2)

有没有听说过JOINing 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';

FROMWHERE部分将选择您的产品id = 33然后您加入product_photo使用不同的别名(是的,您可以多次加入同一个表格)查询)基于product_idorder