2011-06-08 64 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