我在执行以下操作时遇到sql查询问题:
我需要从产品表中选择所有产品,并且我需要从图像表中加入主图像(所有列)。产品图像表包含图像 - 产品关系和列sortWeight。主图像是sortWeight最小的图像。
要获得主要产品图片,我会这样做:
SELECT * FROM images WHERE product=SOME_PRODUCT ORDER BY sortWeight ASC LIMIT 1;
获取所有产品:
SELECT * FROM products;
现在我需要以某种方式加入这两个,但问题是我不知道如何绕过以下限制:
SELECT P.* FROM products AS P
LEFT JOIN
(SELECT * FROM images AS I WHERE I.product=P.id ORDER BY sortWeight ASC LIMIT 1) AS I1
问题是MySQL不知道子查询中的P.id是什么。我也试过这样:
SELECT P.* FROM products AS P
LEFT JOIN
(SELECT * FROM images AS I WHERE ORDER BY sortWeight ASC LIMIT 1) AS I1 ON (I1.product = P.id)
但我不认为这会给出准确的结果,因为子查询有一个限制,它可能会从另一个具有较小sortWeight的产品中选择图像。
任何人都可以帮我改写吗?谢谢。
答案 0 :(得分:3)
尝试将其连接到子查询,该子查询返回每个min
具有最小(product
)sortWeight的图像。
这会返回每个产品的最小sortWeight:
select product, min(sortWeight) as sortWeight
from images
group by product
这是合并版本:
SELECT P.*, i.*
FROM products AS P
left join images as i on p.id = i.product
LEFT JOIN (
select product, min(sortWeight) as sortWeight
from images
group by product
) t on t.product = i.product and i.sortWeight = t.sortWeight