mysql中sql語句中常見的group_concat()函數意思以及用法,oracle中與其一樣的功能函數是wm_concat()
1、group_concat()
手冊上說明:該函數返回帶有來自一個組的連接的非NULL值的字符串結果。比較抽象,難以理解。
通俗點理解,其實是這樣的:group_concat()會計算哪些行屬於同一組,將屬於同一組的列顯示出來。要返回哪些列,由函數參數(就是字段名)決定。分組必須有個標準,就是根據group by指定的列進行分組。
例子:
-- 創建一個計劃表
drop table if exists plan ;
create table plan (
id int PRIMARY key,
name varchar(255)
);
-- 創建一個計劃明細表,是計劃表的子表
drop table if exists planDetail;
create table planDetail(
id int PRIMARY key,
name varchar(255),
state int,
planId int
);
-- 插入數據
insert into plan values(1,'計劃一');
insert into plan values(2,'計劃二');
insert into plan values(3,'計劃三');
insert into planDetail values(1,'明細一',0,1);
insert into planDetail values(2,'明細2',1,1);
insert into planDetail values(3,'明細3',1,1);
insert into planDetail values(4,'明細一',0,2);
insert into planDetail values(5,'明細2',0,2);
insert into planDetail values(6,'明細3',1,2);
insert into planDetail values(7,'明細一',1,3);
insert into planDetail values(8,'明細2',1,3);
insert into planDetail values(9,'明細3',1,3);
現在要查詢每條計劃的所有明細的name,就可以使用group_concat()
select t1.name ,group_concat(t2.name) from plan t1
LEFT JOIN planDetail t2 on T1.id = T2.planid
GROUP BY T1.name
2、wm_concat()
oracle中與其一樣的功能函數是wmsys.wm_concat()也要配合分組查詢group by使用;不使用group by會報錯
select t1.name ,wm_concat(t2.name) from plan t1
LEFT JOIN planDetail t2 on T1.id = T2.planid
GROUP BY T1.name