文章參考http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/sql
首先建表:app
SET FOREIGN_KEY_CHECKS=0;xss
-- ----------------------------
-- Table structure for `fruit`
-- ----------------------------
DROP TABLE IF EXISTS `fruit`;
CREATE TABLE `fruit` (
`type` varchar(10) NOT NULL,
`variety` varchar(20) NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`type`,`variety`),
KEY `type` (`type`,`price`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;ui
-- ----------------------------
-- Records of fruit
-- ----------------------------
INSERT INTO `fruit` VALUES ('apple', 'fuji', '0.24');spa
INSERT INTO `fruit` VALUES ('apple', 'gala', '2.79');blog
INSERT INTO `fruit` VALUES ('apple', 'limbertwing', '2.87');ci
INSERT INTO `fruit` VALUES ('apple', 'seswe', '3.84');it
--------------------------------------------------------------------ast
INSERT INTO `fruit` VALUES ('cherry', 'bing', '2.55');效率
INSERT INTO `fruit` VALUES ('cherry', 'chelan', '6.33');
INSERT INTO `fruit` VALUES ('cherry', 'drtan', '7.33');
INSERT INTO `fruit` VALUES ('cherry', 'drtyd', '7.87');
---------------------------------------------------------------------
INSERT INTO `fruit` VALUES ('orange', 'valencia', '3.59');
INSERT INTO `fruit` VALUES ('orange', 'navel', '9.36');
INSERT INTO `fruit` VALUES ('orange', 'vcxss', '9.43');
INSERT INTO `fruit` VALUES ('orange', 'vbng', '11.33');
INSERT INTO `fruit` VALUES ('orange', 'cccbn', '21.36');
--------------------------------------------------------------------
INSERT INTO `fruit` VALUES ('pear', 'bartlett', '2.14');
INSERT INTO `fruit` VALUES ('pear', 'bradford', '6.05');
INSERT INTO `fruit` VALUES ('pear', 'ddssa', '8.54');
INSERT INTO `fruit` VALUES ('pear', 'rtyug', '9.07');
而後但願獲得每種水果中價格第二高的數據,即:
+--------+------------+-------+ | type | variety | price | +--------+------------+-------+ | apple | limbertwig | 2.87 | | cherry | drtan | 7.33 | | orange | vbng | 11.33 | | pear | ddssa | 8.54 | +--------+------------+-------+
參考以下sql語句:
SELECT t.type,MIN(t.price) price FROM(SELECT
a.type,a.price
FROM fruit a
WHERE
2 >= (
SELECT
COUNT(*)
FROM
fruit b
WHERE
a.type= b.type
AND a.price <= b.price
)
ORDER BY
a.type,
a.price)t
GROUP BY type
本sql使用了兩重子查詢,效率較低。請高人指點~