sql group 分组的时候获取该组的所有id
2016-04-01 10:40
190 查看
sql使用group by 进行分组的时候查找该组的id只会返回一个,只需使用group_concat(id)即可以获得该组的所有id。
创建表;
CREATE TABLE `tb_dept2` (
`id` int(11) NOT NULL,
`name` varchar(22) DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`enum` enum('first','second') DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
插入数据;
+----+--------+----------+-------+
| id | name | location | enum |
+----+--------+----------+-------+
| 1 | 21 | 12 | NULL |
| 2 | 2312 | 32 | first |
| 24 | 2641 | 12 | NULL |
| 25 | 23412 | 32 | first |
| 26 | g34fd | we3 | NULL |
| 39 | g34edd | we3 | |
+----+--------+----------+-------+
未使用:
select id from tb_dept2 group by location;
+----+
| id |
+----+
| 1 |
| 2 |
| 26 |
+----+
使用:
select id,group_concat(id) as ids from tb_dept2 group by location
-> ;
+----+-------+
| id | ids |
+----+-------+
| 1 | 1,24 |
| 2 | 2,25 |
| 26 | 26,39 |
+----+-------+
创建表;
CREATE TABLE `tb_dept2` (
`id` int(11) NOT NULL,
`name` varchar(22) DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`enum` enum('first','second') DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
插入数据;
+----+--------+----------+-------+
| id | name | location | enum |
+----+--------+----------+-------+
| 1 | 21 | 12 | NULL |
| 2 | 2312 | 32 | first |
| 24 | 2641 | 12 | NULL |
| 25 | 23412 | 32 | first |
| 26 | g34fd | we3 | NULL |
| 39 | g34edd | we3 | |
+----+--------+----------+-------+
未使用:
select id from tb_dept2 group by location;
+----+
| id |
+----+
| 1 |
| 2 |
| 26 |
+----+
使用:
select id,group_concat(id) as ids from tb_dept2 group by location
-> ;
+----+-------+
| id | ids |
+----+-------+
| 1 | 1,24 |
| 2 | 2,25 |
| 26 | 26,39 |
+----+-------+
相关文章推荐
- Oracle Study之-AIX6.1构建Oracle 10gR2 RAC(4)
- mysql 自动执行事件
- NoSQL相关资料查找网址
- yum 安装mongodb
- MySQL备份之mysqldump工具--lock-all-tables、--single-transaction以及--lock-tables参数
- 关于mysql varchar 类型的最大长度限制
- sqlite3基本用法
- 数据库 --> 5种关系型数据库比较
- oracle数据库导入和导出的版本兼容性问题
- [整理]:oracle spool 用法
- mysql 优化
- mysql 备份恢复
- mongoDB——wiredTiger副本集模型的成员角色
- oracle 修改字符集 修改为ZHS16GBK
- MySQL遇到check the manual that corresponds to your MySQL server version for the right syntax错误
- sqlplus命令的使用大全
- xUtils3.0 db数据库操作笔记1
- mysql 5.5安装
- 配置oracle数据库可以被其它主机访问
- 如何查询Oracle中用户所有信息