Resolve MySQL group by cannot sort method

Source: Internet
Author: User

The usual method

The code is as follows Copy Code
SELECT * FROM table group BY column_name ORDER by id DESC

is not able to get the maximum value of the ID within each packet.


Workaround:

Someone writes the following statement:

The code is as follows Copy Code


SELECT *,max (Dateline) as Max_line from posts GROUP by Tid order by Dateline DESC LIMIT 10


This statement is correct to select the maximum release time, but you can compare Dateline and max_dateline is not equal! (There may be quite

Situation, that is, the target record of the group is only one time! )

The correct approach is:

The code is as follows Copy Code

SELECT *,max (Dateline) as Max_line from posts GROUP by Tid has Dateline=max (Dateline) Order BY

Dateline DESC LIMIT 10

Or

SELECT * FROM (SELECT * to table ORDER BY id desc) T GROUP BY column_name ORDER by id DESC

This will

The maximum ID value is obtained for each packet, and the last order by id DESC is then sorted by the values of the resulting IDs

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.