Select n rows per group in mysql

こ雲淡風輕ζ 提交于 2020-01-06 04:53:20

问题


I've read this article http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ which solves the problem I have, however I do not quite understand the solution.

Here's the table (from the article).

+--------+------------+-------+
| 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 | 
+--------+------------+-------+

The problem is to chose say 2 smallest rows in terms of the price attribute for each group (by type). One elegant solution the article provides is to do this:

select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type)
   or price = (select min(price) from fruits as f where f.type = fruits.type
      and price > (select min(price) from fruits as f2 where f2.type = fruits.type));

I do not understand using an alias for a whole table like this:

(select min(price) from fruits as f where f.type = fruits.type)

Can anyone explain how this query actually works?


回答1:


You have many solutions and one of them is to use left join and you may check about it

select t1.* from test t1
left join test t2
on t1.type = t2.type and t1.price > t2.price
group by t1.variety
having count(*) <=1
order by t1.type,t1.price

The logic is to do a left join with the same table where the type is same and price is lesser than the other and finally do a group by the varity and then use the count() with having to show the number of records you want per group. Note that in mysql you have a liberty to have a group by clause like in the above query in an arbitrary way which may fail in other RDBMS.

Now as you have some confusion about the alias , in the above example the table name is test and within the query a pseudo name is given as t1. Also when you do a self join its important that you give unique alias names for the same table. In the example above the same table is joined with itself so we need to make sure that we give some alias name for the tables.



来源:https://stackoverflow.com/questions/27463140/select-n-rows-per-group-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!