1. 程式人生 > 其它 >mysql:concat,concat_ws,group_concat

mysql:concat,concat_ws,group_concat

技術標籤:MySQL

文章目錄

1.concat

語法:concat(str1,str2…)
分隔符也作為str傳入

select concat('wyb','♥','xz') as output;

在這裡插入圖片描述

SELECT CONCAT(job_id,':<',min_salary,',',max_salary,'>') AS sal_range FROM jobs;

在這裡插入圖片描述

2.concat_ws

語法:concat_ws(sep,str1,str2,…)
當Separator一樣並且有多個時,使用concat要把這些重複的sep一個一個寫出來,很麻煩,可以使用concat_ws來簡化(concat_ws就是concat with Separator的縮寫)

select concat_ws('~','wyb','xz','zql','hjy') as output;

在這裡插入圖片描述

3.group_concat

語法:group_concat(var order by col_name separator ‘,’)
SQL中group_concat的用法和hive中collect_list()的用法差不多,即將一列變數值用指定分隔符連線起來,分隔符預設為逗號;此外它還可以對變數值進行排序,即先排序,然後再用分隔符連線起來。

select group_concat(brand_name separator '、') as brand from jd.brands;

在這裡插入圖片描述
經典例題:求某個表的所有變數名

--求brands這個表中的所有變數名,用'/'連線,結果以col_names命名
select group_concat(column_name separator '/')  as col_names
from information_schema.columns
where table_schema='jd' and table_name='brands';

在這裡插入圖片描述
information_schema是一個庫,columns是其中的一張表,裡面放了所有庫中所有表的變數資訊

SELECT department_id,
GROUP_CONCAT(CONCAT(
employee_id,'-',first_name) ORDER BY employee_id SEPARATOR ',') AS dept_employees FROM employees GROUP BY department_id;

在這裡插入圖片描述

SELECT GROUP_CONCAT(first_name ORDER BY salary DESC SEPARATOR '>') AS sal_output
FROM employees WHERE salary>15000;

在這裡插入圖片描述