Mysql 如何从一对多关系中仅连接一行,其中值为最小值或最大值?
我有两张桌子:Mysql 如何从一对多关系中仅连接一行,其中值为最小值或最大值?,mysql,sql,Mysql,Sql,我有两张桌子: 产品: id|name 1|first 2|second 产品单元: 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
产品
:
id|name
1|first
2|second
产品单元
:
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
2|second|30
因为id=1的产品的最低价格10低于15
对此的正确查询是什么?
(如果可能的话,我宁愿不使用派生表)使用派生表的一种方法
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 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
我想看看HAVING条款……谢谢你的回复,我想这会有用的。我更喜欢没有派生表,但可能没有派生表是不可能的。现在我需要为拉威尔改编这部电影。
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