常用sql 2018.08.31

concat()函数

concat(str1, str2,...)
功能:将多个字符串连接成一个字符串
返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null。

如:CONCAT(a.MinNum,'~',a.MaxNum) 

concat_ws()函数
concat_ws(separator, str1, str2, ...)
功能:和concat()一样,将多个字符串连接成一个字符串,但是可以一次性指定分隔符~(concat_ws就是concat with separator)

group_concat()函数
group_concat(要连接的字段)
group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'] )
功能:通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,默认为一个逗号

如:GROUP_CONCAT(a.ChineseName  ORDER BY b.Id SEPARATOR '、') 

CASE when then详见
case 枚举字段 when 枚举值1 then '值1' when 枚举值2 then '值2' end
功能: 结合sum()、count()可实现分段统计。

SELECT
(CASE (SELECT COUNT(a) FROM A ) WHEN 0 THEN '值1' ELSE '值2' END )
FROM role
-- 可统计后,根据统计结果得出不同场景

如:

SELECT
(case a.TaskState when 1 then '未开始' when 2 then '已开始' WHEN 3 THEN '生效中' WHEN 4 THEN '已生效' end) '状态'  from A

子查询:not exists

 不存在

select * from A  where not exists ( select * from B where XXXX)

指定排序

order by find_in_set(a.id,'2,3,4') 

原文地址:https://www.cnblogs.com/ericazy/p/9564302.html