简体   繁体   中英

MySQL find rows with max value of a field

I have a complex SELECT query which returns info like this:

+------+-------+--------+
| a    | b     | c      |
+------+-------+--------+
| 2482 |  3681 |  58248 |
| 2482 | 17727 | 139249 |
| 2482 | 23349 | 170839 |
| 3031 | 14877 | 122921 |
| 3031 | 20691 | 156457 |
| 3031 | 20932 | 157784 |
+------+-------+--------+

and I'm trying to work out how to return just the rows with the maximum value of b for each value of a. The solution in here looked promising but I was unable to make it work since my starting point isn't a table but a query (or view, I guess), and I get an error

"ERROR 1146 (42S02): Table 'databasename.s' doesn't exist"

when I try to refer to the subquery in the fashion of the above question:

select s.* from (SELECT blah blah complex) s where s.b = (select max(s2.b) from s s2 where s2.a = s.a);

I'm pretty certain this is a semi-trival problem but I've bashed my head off it for hours and simply don't understand it well enough to navigate my way out of it...

Edit: I should have clarified what I want to get as output:

    +------+-------+--------+
    | a    | b     | c      |
    +------+-------+--------+
    | 2482 | 23349 | 170839 |
    | 3031 | 20932 | 157784 |
    +------+-------+--------+

MySQL version is 5.5.49 (Ver 14.14 Distrib 5.5.49)

UPDATE: @Harshil's answer clarified that what I was attempting was essentially impossible, so I ended up following the guidance in other questions (guided by @Bill Karwin's commment) and rewrote my original query to perform another JOIN (against a subquery) which does the max().

 select a,b,c from examp where (a,b) in (select a ,max(b) from examp group by a );

The alias s can't be visible in subquery. So you have to write it again in subquery. Also use group by instead of where clause as follows:

select s.* 
  from 
     (SELECT blah blah complex) s 
        where (s.a,s.b) in (select s2.a,max(s2.b) from (SELECT blah blah complex) group by s2.a);

Alternatively, create view of query (SELECT blah blah complex) for ie named V and use it in your main query as follows:

select * 
  from V
     where (a,b) in (select v2.a,max(v2.b) from V as v2 group by v2.a);

Hope it helps!

Firstly, use

SELECT * INTO newTableName 

FROM yourRules 

to save the query to a new table.

Then we can do another select from the new table.

SELECT *
FROM newTableName t1
WHERE b = (
     SELECT max(b) 
     FROM newTableName t2
     WHERE t1.a = t2.a
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM