举例
比如现在有两个表tbl_a和tbl_b,如下:
tbl_a
id | name |
---|---|
1 | Bruce |
2 | Mike |
3 | Angela |
tbl_b
id | a_id | hobby |
---|---|---|
1 | 1 | Basketball |
2 | 1 | Basketball |
3 | 2 | Watching TV |
4 | 3 | Shopping |
5 | 3 | Shopping |
6 | 3 | Shopping |
这时候我们如果联查的话,就会出现重复数据:
select a.id, a.name from tbl_a a
join tbl_b b on a.id = b.a_id
where …
这样查出来的数据就会像下面这样:
id | name |
---|---|
1 | Bruce |
1 | Bruce |
2 | Mike |
3 | Angela |
3 | Angela |
3 | Angela |
解决
去重的方法有三种:
一、distinct
select distinct a.id, a.name from tbl_a a
join tbl_b b on a.id = b.a_id
where …
二、group by
select a.id, a.name from tbl_a a
join tbl_b b on a.id = b.a_id
where …
group by a.id
三、子查询
select a.id, a.name from tbl_a a
where a.id = (select a_id from tbl_b where a_id = a.id)
count怎么办?
如果要用count统计数据,直接按最开始的写法也会统计多出来,而且此时distinct和group by也不好用了。
distinct直接没效果,group by则变成了按tbl_a的id分别统计个数。
这时候就只能用子查询来解决问题了。
网友评论