2014-02-10 46 views
0

我如何獲得MySQL中的第二個最大ID?我如何獲得MySQL中的第二個最大ID?

看到我的代碼和圖片波紋管:

enter image description here

SET FOREIGN_KEY_CHECKS=0; 

-- ---------------------------- 
-- Table structure for `a` 
-- ---------------------------- 
DROP TABLE IF EXISTS `a`; 
CREATE TABLE `a` (
    `id` int(11) NOT NULL auto_increment, 
    `name` varchar(30) default NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; 

-- ---------------------------- 
-- Records of a 
-- ---------------------------- 
INSERT INTO `a` VALUES ('1', 'jimy'); 
INSERT INTO `a` VALUES ('7', 'khon'); 
INSERT INTO `a` VALUES ('3', 'tina'); 
INSERT INTO `a` VALUES ('4', 'kelvin'); 
INSERT INTO `a` VALUES ('5', 'ricky'); 

回答

0

試試這個:

select max(id) from a where id != (select max(id) from a) 
3

使用limit子句:

select * 
from a 
order by id desc 
limit 1, 1 
2

我喜歡戈登·利諾夫的答案,同時提供我的醜條款:

select min(id) as id from 
     (select * from a order by id desc limit 2) as temp_table; 
0

最簡單的方法來獲取第二最高工資&第n工資

select 
DISTINCT(salary) 
from employee 
order by salary desc 
limit 1,1 

注:

limit 0,1 - Top max salary 

limit 1,1 - Second max salary 

limit 2,1 - Third max salary 

limit 3,1 - Fourth max salary 
相關問題