Ask a MySQL question. About getting the maximum value of a field in a query result (sorted by another field)

Source: Internet
Author: User
Every time I ask for such a question is quite embarrassed ... But it's often too late to find a way to check the manual. Had to reach out again.

The problem is this. Make a regular query, in reverse order by field a. But want to get the maximum value of field B in this query

PHP does not seem to provide a function to get the maximum key value of a multidimensional array directly. To write their own sort is not impossible, but still want to ask in the MySQL side can be directly detected (and can not have too much performance loss or not as far as the PHP calculation)

Thank you


Reply to discussion (solution)

MySQL provides a max function, but this is a clustering function that is not suitable for your scene

Is it not necessary to have a loop when extracting data? In the loop by the means (with the Max function) is not OK?

MySQL provides a max function, but this is a clustering function that is not suitable for your scene

Is it not necessary to have a loop when extracting data? In the loop by the means (with the Max function) is not OK?

Well, if it's not convenient for MySQL, then it's still PHP. I now extract the value of field B into an array and then Arsort () and take the first one.

$m = 0;
while ($row = Mysql_assoc ($rs)) {
$res [] = $row; This is the usual data reception
$m = Max ($m, $row [' B ']); By the way, calculate the maximum value of column B
}



Ask a question, when MySQL queries, multiple where conditions will their ordering affect the efficiency of the query?

Suppose there are 1 million records

Will the efficiency change with the id>500000 and B fields <> "" Two conditions swap positions?

There is no index is critical

  • Related Article

    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.