How to query the latest information of all users in MySQL?

WBOY
Release: 2016-08-04 09:21:27
Original
1058 people have browsed it

I thought of using group by, but it can only display the first one, not the latest one.
I want to add an order by time desc, but orber by can only be added after group by.

Is there any way to query the largest or smallest row of data in each group in the group by?

Reply content:

I thought of using group by, but it can only display the first one, not the latest one.
I want to add an order by time desc, but orber by can only be added after group by.

Is there any way to query the largest or smallest row of data in each group in the group by?

Option 1: Find the largest data ID through subquery or join in the same table

<code>select * from track where id in(select max(id)  from track group by target_id);

or

select * from track where id in(select substring_index(group_concat(id order by id desc),',',1) as maxid from track group by target_id);</code>
Copy after login

Option 2: Query in two steps, first query the maximum ID in php, and then query the list data through the ID array

select a.* from(select max(id) as id from info group by userid) b left join info a on a.id=b.id

Save the query results and retrieve them later

Use order by

<code>select * from ( 
    select (@mycnt := @mycnt + 1) as ROWNUM,name,age
    from tb where AGe < 20 order by name,age 
) as A where ROWNUM = 1
</code>
Copy after login

I only know SqlServer, this is written in imitation of SqlServer, you can try it

<code>SELECT a.id, a.user_id, a.info, a.create_time
    FROM (SELECT id, user_id, info, create_time FROM tbl_user 
        ORDER BY user_id, create_time DESC, id DESC) a
    GROUP BY a.user_id</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!