简体   繁体   中英

Get the last id in a Grouped Mysql query

SELECT * 
  FROM 
     ( SELECT * 
         FROM notifications 
        ORDER   
           BY id DESC
     ) t 
 WHERE t.userTo = '".$myId."' 
 GROUP 
    BY t.postId
     ,  t.dataId
     ,  t.type

I used the above code trying to order the table in a descending order before grouping the rows so I will get the last row in every group but instead I get the first row.

The code works fine in Mysql5.5.8 but after upgrading my WAMP SERVER which runs with MySQL5.7.14 the code isn't working

Please any idea on how to fix this?

Try this query

SELECT n.*
FROM notifications n
JOIN
  (
    SELECT postId,dataId,type,MAX(id) LastID
    FROM notifications
    WHERE userTo='...'
    GROUP BY postId,dataId,type
  ) l
ON n.postId=l.postId AND n.dataId=l.dataId AND n.type=l.type AND n.id=l.LastID
ORDER BY n.id DESC

SQL Fiddle - http://sqlfiddle.com/#!9/4436b9/3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM