简体   繁体   中英

Select all columns from a table where each user_id is different

I am creating an activity feed displaying my users activity that is limited to the last 5 rows.

SELECT * FROM activity ORDER BY date desc LIMIT 5

The problem is I don't want the activity feed to be cluttered by the same user at any point so I want to retrieve the last 5 results where the user_id's are different from each other.

How could I go about doing this?

这应该工作:

SELECT user_id, MAX(date) FROM activity GROUP BY user_id ORDER BY date DESC LIMIT 5

If there are no multiple max(date) for each user, you could use this:

SELECT *
FROM   activity
WHERE  (user_id, `date`) IN (
  SELECT * FROM (
    SELECT   user_id, max(`date`)
    FROM     activity
    GROUP BY user_id
    ORDER BY max(`date`) DESC
    LIMIT 5) s
  )
ORDER BY `date` DESC

Please see fiddle here .

I suppose it would be an easy thing using a query like

SELECT DISTINCT activity.user_id,activity.* order by date DESC limit 5

Mysql Distinct reference : http://dev.mysql.com/doc/refman/5.1/en/distinct-optimization.html

它可以帮助您。

SELECT * FROM activity GROUP BY user ORDER BY date DESC LIMIT 5

试试这个查询,SELECT DISTINCT * FROM activity ORDER BY date desc LIMIT 5

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