开发者

1st Row in Group By vs. Last Row

开发者 https://www.devze.com 2023-04-12 05:03 出处:网络
Wondering how to return the 1st row in a MySQL group by vs. the last row. Returning a series of dates, but need the first one displayed.

Wondering how to return the 1st row in a MySQL group by vs. the last row. Returning a series of dates, but need the first one displayed.

select * from calendar where approv开发者_如何转开发ed = 'pending' group by eventid; 


Sounds like you want to use ORDER BY instead of GROUP BY:

select * from calendar where approved = 'pending' order by eventid asc limit 1;


Use the min function insead of max to return the first row in a group vs the last row.

select min(date) from calendar ...

If you want the entire row for each group, join the table with itself filtered for the min dates on each group:

select c2.* from
    (select eventid, min(dt) dt from calendar
        where approved = 'pending' group by eventid) c1
inner join calendar c2 on c1.eventid=c2.eventid and c1.dt=c2.dt
group by eventid;

Demo: http://www.sqlize.com/6lOr55p67c


When you use GROUP BY like that, MySQL makes no guarantees about which row in each group you get. Indeed, theoretically it could even pick some of the columns from one row and some from another. The MySQL Reference Manual says:

"MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. [...] You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

What you want to do instead is something like this:

SELECT
  calendar.*
FROM
  calendar
  NATURAL JOIN (
    SELECT
      eventid, MIN(date) AS date
    FROM
      calendar
    GROUP BY eventid
  ) AS foo


If you want to show the first AND the last element of a group-by statement, this was useful for me:

SELECT min(date) AS minn, max(date) AS maxx 
FROM table_name
GROUP BY occasion

Thanks for the question


I have the solution. To select the last row in a group, use this

select * from calendar 
where approved = 'pending' 
group by eventid 
ORDER BY max(`date`) DESC; 

or this to select the first row from a group...

select * from calendar 
where approved = 'pending' 
group by eventid 
ORDER BY min(`date`) DESC; 

The DESC does not matter, it only sorts the entire filtered result by descending order, after a row from each group has been selected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号