Mysql 从每组中选择最多一行
在示例Xaprb中 为每个组选择最大值Mysql 从每组中选择最多一行,mysql,correlated-subquery,Mysql,Correlated Subquery,在示例Xaprb中 为每个组选择最大值 +--------+------------+-------+ | type | variety | price | +--------+------------+-------+ | apple | gala | 2.79 | | apple | fuji | 0.24 | | apple | limbertwig | 2.87 | | orange | valencia | 3.59 | |
+--------+------------+-------+
| type | variety | price |
+--------+------------+-------+
| apple | gala | 2.79 |
| apple | fuji | 0.24 |
| apple | limbertwig | 2.87 |
| orange | valencia | 3.59 |
| orange | navel | 9.36 |
| pear | bradford | 6.05 |
| pear | bartlett | 2.14 |
| cherry | bing | 2.55 |
| cherry | chelan | 6.33 |
+--------+------------+-------+
select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);
+--------+----------+-------+
| type | variety | price |
+--------+----------+-------+
| apple | fuji | 0.24 |
| orange | valencia | 3.59 |
| pear | bartlett | 2.14 |
| cherry | bing | 2.55 |
+--------+----------+-------+
但是如果我有一个水果和一些价格记录是重复的
+--------+----------+-------+
| type | variety | price |
+--------+----------+-------+
| apple | fuji | 0.24 |
| apple | fuji2 | 0.24 |
| orange | valencia | 3.59 |
| pear | bartlett | 2.14 |
| cherry | bing | 2.55 |
+--------+----------+-------+
在这种情况下,每个类型如何只能获得一条记录?只需按
类型分组即可
select type, MIN(variety) AS variety, MIN(price) AS price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);
GROUP BY type
这是你得到的第一个项目(按字母顺序)
顺便说一句:您也可以使用MAX
,这正是您喜欢的使用GROUPBY子句-即
select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type)
group by type;
我不能使用组,在选择我使用的列中,不参与组和聚合功能,然后给我们完整的select
声明,因此有类型
,品种
和价格
?如果是这样,为什么我的声明不起作用?