码迷,mamicode.com
首页 > 数据库 > 详细

SQL -- group, having

时间:2015-08-09 15:20:18      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

SQL – group, having

SQL – group, having

Table of Contents

group

truncate table user1;

insert into user1 (id, username) values (1, ‘test1‘);
insert into user1 (id, username) values (2, ‘test1‘);
insert into user1 (id, username) values (3, ‘test1‘);
insert into user1 (id, username) values (4, ‘test1‘);
insert into user1 (id, username) values (5, ‘test1‘);

insert into user1 (id, username) values (1, ‘test2‘);
insert into user1 (id, username) values (2, ‘test2‘);
insert into user1 (id, username) values (3, ‘test2‘);
insert into user1 (id, username) values (4, ‘test2‘);
insert into user1 (id, username) values (5, ‘test2‘);

insert into user1 (id, username) values (1, ‘test3‘);
insert into user1 (id, username) values (2, ‘test3‘);
insert into user1 (id, username) values (3, ‘test3‘);
insert into user1 (id, username) values (4, ‘test3‘);
insert into user1 (id, username) values (5, ‘test3‘);
select * from user1 group by username;
| id | username |
+----+----------+
|  1 | test1    |
|  1 | test2    |
|  1 | test3    |
select * from user1 group by id;
| id | username |
+----+----------+
|  1 | test1    |
|  2 | test1    |
|  3 | test1    |
|  4 | test1    |
|  5 | test1    |

分组实际上就是求集合?

select username, id from user1 group by 1;

1 指的是 username, group by 2 指的是 id (一般不这样用, 好丑陋的用法)

having

相当于 where

select username, id from user1 group by id;
| username | id |
+----------+----+
| test1    |  1 |
| test1    |  2 |
| test1    |  3 |
| test1    |  4 |
| test1    |  5 |
select username, id from user1 group by id having id in (1, 2, 3);
| username | id |
+----------+----+
| test1    |  1 |
| test1    |  2 |
| test1    |  3 |
select username from user1 group by id having id in (1, 2, 3);
select username from user1 group by username having id in (1, 2, 3);   # 报错, 没有 id 这个字段

SQL -- group, having

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4715063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!