Group by user and show latest in MYSQL not working

戏子无情 提交于 2019-12-10 12:13:15

问题


I have a social network I am coding but it's a bit different than others, in this case there is only ever one status show per user on a feed section.

So I need to sort the status by date with the latest ones on top but also group by the userID unfortunately I can't seem to get this working....

This is my current query:

SELECT *
FROM status
WHERE userID != "83" #This is just so my statuses don't show
GROUP BY userID
ORDER BY addedDate DESC
LIMIT 10

I expect to see the latest status results and only one per user instead I see the first statuses so the group by is working but not the order by.

Thanks in advance.


回答1:


As mentioned in the comments to Robin's answer, that approach is unreliable because MySQL does not guarantee that it will always return the most recent status from each group. You must instead join your table with a subquery that selects the most recent status (based on addedDate).

SELECT   *
FROM     status
  NATURAL JOIN (
    SELECT   userID, MAX(addedDate) as addedDate
    FROM     status
    GROUP BY userID
  ) AS mostRecent
ORDER BY addedDate DESC
LIMIT    10

Note that if a user has multiple status updates with the same addedDate, the server will return all of them (whereas Robin's query would return an indeterminate one); if you need control over such a situation, you will need to define how one determines which such status update should be selected.




回答2:


SELECT userID, max(addedDate)
FROM status
WHERE userID != "83" #This is just so my statuses don't show
GROUP BY userID



回答3:


SELECT *
FROM (  SELECT *
        FROM status
        WHERE userID != "83"
        ORDER BY addedDate DESC) AS h
GROUP BY userID
ORDER BY addedDate DESC
LIMIT 10

You must ORDER BY before GROUP BY'ing.

Example 1
Example 2



来源:https://stackoverflow.com/questions/10550386/group-by-user-and-show-latest-in-mysql-not-working

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