mysql 多行合并一列 使用的函数为:
GROUP_CONCAT(exp)
其中exp 的参数类似如下:
(field order by field desc separator ';');
具体的例子如下:
创建表:
CREATE TABLE `login` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=gbk;
添加数据:
insert into login(id,name) values(3,'dalong'); insert into login(id,name) values(4,'dalong'); insert into login(id,name) values(5,'dalong'); insert into login(id,name) values(6,'dalong'); insert into login(id,name) values(7,'app'); insert into login(id,name) values(8,'app'); insert into login(id,name) values(9,'app');
测试结果:
按照name 排序获取id 的组合:
sql 如下:
select name,group_concat(id order by id desc separator ';') from login group by name;
测试结果: