如何从一对多关系中仅连接一行,其中值为min或max?

时间:2016-03-17 13:16:32

标签: mysql sql

我有两张桌子:

products

id|name
1|first
2|second

product_unit

id|product_id|price
1|1|10
2|1|20
3|2|40
4|2|30

我想选择最小值大于15且小于35的产品。第一产品最小值为10,第二产品最小值为30。

现在我有这个问题:

select products.*, min(product_unit.price) as min_price
from `products`
left join `product_unit`
    on  `product_unit`.`product_id` = `products`.`id`
    and (`product_unit`.`value` > '15' and `product_unit`.`value` < '35') 
group by `products`.`id`

此查询返回:

id|name|price
1|first|20
2|second|30

但是应该:

id|name|price
2|second|30

因为id = 1的产品的最低价格10低于15.

对此有什么正确的查询? (如果可能,我希望没有派生表)

1 个答案:

答案 0 :(得分:2)

使用派生表执行此操作的一种方法。

select p.id, p.name, t.minprice as price 
from products p
join (select product_id,min(price) as minprice 
      from product_unit
      group by product_id) t
on t.product_id = p.id
where t.minprice > 15 and t.minprice < 35

select p.id, p.name, t.minprice as price 
from products p
join (select product_id,min(price) as minprice 
      from product_unit
      group by product_id
      having min(price) between 16 and 34) t
on t.product_id = p.id

或没有派生表

select pu.product_id,p.name,min(pu.price) as minprice 
from product_unit pu
join products p on pu.product_id = p.id
group by pu.product_id,p.name
having min(pu.price) between 16 and 34