條件:
查詢出學生最後一次的成績。
全部數據顯示:
mysql5.6
使用sql:
select a.score,a.name from ( select * from hehe order by id desc ) a group by a.name;
結果:
mysql5.7
使用同樣語句:
可以看出order by失效了
5.7官方手冊給出:
It must not have ORDER BY with LIMIT.
他們說order by 如果沒有加limit 就會失效
加上limit:
可以了
第二種方法:
使用:substring_index 和concat_group函數
5.6 5.7均可
SELECT SUBSTRING_INDEX(GROUP_CONCAT(score ORDER BY id desc),',',1) as score,name from hehe group by name;
小李的是90 上一個是null concat_group 把小李最新成績爲null的過濾掉了 大家根據情況使用
簡單介紹下substring_index:
substring_index(str,delim,count)
說明:substring_index(被截取字段,關鍵字,關鍵字出現的次數)
concat_group
一、concat()函數
功能:將多個字符串拼接成一個字符串
語法:concat(str1,str2,…)
返回結果爲連接參數產生的字符串 如果有任何一個參數爲NULL 則返回值NULL
select concat(name,score) from hehe;
select concat(period,',',award) as info from collect_ahsyxw;
注:-符號 如果參數多的話 需要更多的-符號 因此需要concat_ws()
二、concat_ws()函數
功能:一次性指定分隔符
語法:concat_ws(separator,str1,str2,…)
說明:第一個參數指定分隔符 分隔符不能爲空 如果爲NULL 則返回值NULL
select concat(',',name,score) from hehe;
select concat_ws(null,name,score) from hehe;
三、group_concat()函數
序:在有group by查詢語句中 select指定的字段要麼包含在group by語句後面 作爲分組的依據
要麼就包含在聚合函數中
例子:
select name,min(id) from hehe group by name;
select id,name from hehe order by name;
1.功能:將group by產生的同一個分組中的值連接起來 返回一個字符串結果
2.語法 group_concat([distinct]要連接的字段 [order by 排序字段 asc/desc][separator’分隔符’])
說明:通過使用distinct可以排除重複值 如果希望對結果中的值進行排序 可以使用order by子句 separator是一個字符串值
缺省爲一個逗號
舉例:
使用group_concat()和group by顯示相同名字的人的id號
舉例:
將上面的id號從小到大排序 且用’_'作爲分隔符:
舉例:以name分組的所有組id和score
id和score連在一起 看的不是那麼直觀 使用concat_ws() 對每組中的id,score進行分割