In-depth study of the latest time for retrieving classification between groupby and orderby in mysql _ MySQL
Source: Internet
Author: User
In-depth study of the latest time content bitsCN.com of groupby and orderby in mysql
This article will take a closer look at group by and order by in mysql. below is my content table simulation
Now I need to retrieve the latest content in each category. select * from test group by category_id order by 'date'. The result is as follows:
Obviously. This is not the data I want, because the execution sequence of msyql is the order of reference writing: select... from... where .... group... having... order .. execution sequence: from... where... group... having .... select... order... therefore, the result obtained by order by is the final result of grouping. The result from where to from is as follows.
At group by, multiple groups are obtained according to category_id.
When the select statement is adopted, the result is as follows:
Even order by is sorted from the above results. -- Not the latest information for each category. Return to my goal-the latest information in the category. according to the above analysis, only the first information in the group is obtained when group by is selected. There are two solutions: 1. where + group by (sort groups) 2. the data returned from the form is under the hand (I .e. subquery)
The where + group by function sorts groups in group by. I only find that group_concat () can be sorted, however, group_concat is used to concatenate values in fields in a group. Select group_concat (id order by 'date' desc) from 'test' group by category_id
Next, let's improve the select * from 'test' where id in (select SUBSTRING_INDEX (group_concat (id order by 'date' desc), ',', 1) from 'test' group by category_id) order by 'date' desc
Subquery solution select * from (select * from 'test' order by 'date' desc) 'temp 'group by category_id order by 'date' desc
From Wang He's blog bitsCN.com
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service