2011-06-08 63 views
2

如何在MAX之前选择第一,第二或第三个值?MySQL之前的MySQL选择值

通常我们用为了做到这一点,并限制

SELECT * FROM table1 
ORDER BY field1 DESC 
LIMIT 2,1 

,但我目前的查询我不知道如何使它...

样品表

+----+------+------+-------+ 
| id | name | type | count | 
+----+------+------+-------+ 
| 1 | a | 1 |  2 | 
| 2 | ab | 1 |  3 | 
| 3 | abc | 1 |  1 | 
| 4 | b | 2 |  7 | 
| 5 | ba | 2 |  1 | 
| 6 | cab | 3 |  9 | 
+----+------+------+-------+ 

我将这个查询的每个类型的名称与最大数联系起来

SELECT 
    `table1b`.`name` 
FROM 
    (SELECT 
     `table1a`.`type`, MAX(`table1a`.`count`) AS `Count` 
    FROM 
     `table1` AS `table1a` 
    GROUP BY `table1a`.`type`) AS `table1a` 
     INNER JOIN 
    `table1` AS `table1b` ON (`table1b`.`type` = `table1a`.`type` AND `table1b`.`count` = `table1a`.`Count`) 

,我想多了一个额外的列值为命名之前最大(计数)

所以结果应该是

+------+------------+ 
| name | before_max | 
+------+------------+ 
| ab |   2 | 
| b |   1 | 
| cab |  NULL | 
+------+------------+ 

请问,如果事情是不明确;)

回答

1

按您给定表(测试)结构,查询具有如下:

select max_name.name,before_max.count 
from 
(SELECT type,max(count) as max 
FROM `test` 
group by type) as type_max 
join 
(select type,name,count 
from test 
) as max_name on (type_max.type = max_name.type and count = type_max.max) 

left join 
(select type,count 
from test as t1 
where count != (select max(count) from test as t2 where t1.type = t2.type) 
group by type 
order by count desc) as before_max on(type_max.type = before_max .type) 
+0

谢谢:)这是真棒,我无法弄清楚,也该给我一个线索如何米更复杂的查询:) – davispuh 2011-06-10 20:55:40