how to find first and last record from mysql table

前端 未结 5 1856
失恋的感觉
失恋的感觉 2020-12-11 00:59

I have one table I want to find first and last record that satisfy criteria of particular month.

5条回答
  •  有刺的猬
    2020-12-11 01:18

    How about something like:

    select 'first', f1, f2, f3, f4 from tbl
        order by f1 asc, f2 asc
        limit 1
    union all
    select 'last', f1, f2, f3, f4 from tbl
        order by f1 desc, f2 desc
        limit 1
    

    Obviously feel free to add whatever condition you want in a where clause but the basic premise of the order by is to reverse the order in the two select sections.

    The limit clause will just get the first row in both cases. That just happens to be the last row of set in the second select due to the fact that you've reversed the ordering.

    If there is only one row resulting from your conditions and you don't want it returned twice, use union instead of union all.

提交回复
热议问题