This article will take a closer look at group by and order by in mysql. below is my content table simulation
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
Reference
Write order: select... from... where... group by... having... order ..
Execution sequence: from... where... group by... 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.
Back 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 form has the following hands and feet (I .e., subquery)
Solution by where + group
I only find that group_concat () can be used to sort groups in group by, but group_concat is used to concatenate values in fields in the group.
Select group_concat (id order by 'date' desc) from 'test' group by category_id
Try again
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
Example
Copy codeThe Code is as follows:
SELECT * FROM (SELECT * FROM 'ecm _ copy_goods_change 'order BY 'cid' DESC) 'ecm _ copy_goods_change 'group BY goods_id order by 'cid' DESC