左连接只对应表的一个结果

时间:2014-10-08 12:38:30

标签: mysql sql

我有以下表格:

products: id INT title VARCHAR

offers: id INT product_id INT price INT

产品可以有很多优惠。我需要以更低和更高的价格获得所有相应优惠的产品,我所拥有的是:

SELECT products.id, products.title, lowOffer.price, highOffer.price
FROM products

LEFT JOIN (SELECT offers.product_id, MIN(offers.price) AS price FROM offers GROUP BY offers.product_id) AS lowOffer ON (lowOffer.product_id = products.id)


LEFT JOIN (SELECT offers.product_id, MAX(offers.price) AS price FROM offers GROUP BY offers.product_id) AS highOffer ON (highOffer.product_id = products.id)

现在,我正在做两个子查询,我想我只能有一个子查询,因为这两个连接正在处理同一组提议。我怎么能这样做?

我的业务逻辑比这更复杂一点,优惠本身也有关系,我也必须带来它们。我怎样才能以有效的方式做到这一点?我不想在不需要的情况下进行连接。

1 个答案:

答案 0 :(得分:1)

您可以离开加入,然后在顶层使用GROUP BY

SELECT
    p.id
,   p.title
,   MIN(o.price) as min_price
,   MAX(o.price) AS max_price
FROM products p
LEFT JOIN offers o ON o.product_id = p.id
GROUP BY p.id, p.title