CREATE TABLE `grade1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `stuName` varchar(22) DEFAULT NULL, `course` varchar(22) DEFAULT NULL, `score` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of grade1 -- ---------------------------- INSERT INTO `grade1` VALUES ('1', '張三', '語文', '91'); INSERT INTO `grade1` VALUES ('2', '張三', '數學', '90'); INSERT INTO `grade1` VALUES ('3', '張三', '英語', '87'); INSERT INTO `grade1` VALUES ('4', '李四', '語文', '79'); INSERT INTO `grade1` VALUES ('5', '李四', '數學', '95'); INSERT INTO `grade1` VALUES ('6', '李四', '英語', '80'); INSERT INTO `grade1` VALUES ('7', '王五', '語文', '77'); INSERT INTO `grade1` VALUES ('8', '王五', '數學', '81'); INSERT INTO `grade1` VALUES ('9', '王五', '英語', '89');
表內容如上圖.net
先看看group_concat語法: group_concat([DISTINCT] 要鏈接的字段 [Order BY ASC/DESC 排序字段] [Separator ‘分隔符’])code
以stuName分組,把score字段的值打印在一行,逗號分隔(默認)blog
select GROUP_CONCAT(score),stuName from grade1 GROUP BY stuName;
其結果是:排序
那好比如今要查詢出 語數外三門課的最低分,還有哪一個學生考的?該怎麼寫??圖片
select GROUP_CONCAT(stuName ORDER BY score ASC), min(score) as score, course from grade1 group by course;
其結果是:字符串
在結果中的第一列 ,有不少姓名而且以逗號隔開,其實這裏的姓名就是按照score 升序排的(GROUP_CONCAT(stuName ORDER BY score ASC)),好比第一行的」王五,張三,李四」,就是按照數學的分數由低到高排序的,因此王五是數學分數最低的,那麼咱們只須要把這個字符串截取第一我的的名字就能夠了,咱們使用 SUBSTRING_INDEXget
/*SUBSTRING_INDEX以逗號分隔,取第一個值*/ select SUBSTRING_INDEX(GROUP_CONCAT(stuName ORDER BY score ASC),',',1), min(score) as score, course from grade1 group by course;
其結果是:數學
若是有並列最低分只能取到一個學生,能夠這樣修改,並列最低均可以查出:it
SELECT stuName, score, course FROM grade1 WHERE (score, course) IN ( SELECT min(score), course FROM grade1 GROUP BY course );
第一種若是有並列最低分只能取到一個學生,第二種沒問題,不過效率可能會稍差點,數據量少就無所謂了效率
還有一種寫法(不知道效率怎麼樣):
SELECT g.`id`,g.`course`,g.`score`,g.`stuName` FROM (SELECT course, SUBSTRING_INDEX( GROUP_CONCAT(score ORDER BY score ASC), ',', 1 ) AS score FROM grade1 GROUP BY course) AS t LEFT JOIN grade1 AS g ON ( t.course = g.`course` AND t.score = g.`score` )
友情連接http://blog.csdn.net/ys410900345/article/details/44828571