Ask a mysql question. obtain the maximum value of a field in the query result (sort by other fields)

Source: Internet
Author: User
Ask a mysql question. I am very embarrassed to obtain the maximum value of a field in the query result (sorted by other fields... however, it is often too late to go to the manual to find a solution... I had to extend my hand...

This is the problem. perform a regular query and sort by field a in reverse order. However, you want to obtain the maximum value of field B in this query.

Php does not seem to provide a function to directly obtain the maximum key value of a multi-dimensional array .. it's not impossible to write and sort by yourself, but I still want to ask if I can find it directly on the mysql side (and there cannot be too much performance loss; otherwise, I 'd better use php to calculate it)

Thank you.


Reply to discussion (solution)

Mysql provides max functions, but this is a clustering function and is not suitable for your scenarios.

Isn't there a loop to retrieve data? In the Loop, is it okay if I use the max function?

Mysql provides max functions, but this is a clustering function and is not suitable for your scenarios.

Isn't there a loop to retrieve data? In the Loop, is it okay if I use the max function?

Well, if mysql is inconvenient, use php for computation. Currently, I have extracted all the values of field B to an array, then arsort (), and then the first one.

$ M = 0;
While ($ row = mysql_assoc ($ rs )){
$ Res [] = $ row; // This is the usual data reception
$ M = max ($ m, $ row ['B']); // calculate the maximum value of column B by the way.
}

?

Q: Will the sorting of multiple where conditions during mysql Query affect the query efficiency?

Assume there are 1 million records

Will the efficiency change if I swaps the positions of the fields id> 500000 and B <>?

Whether or not an index is critical

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.