赞
踩
我们在使用left join联表查询时,如果table1中的一条记录对应了table2的多条记录,则会重复查出id相同的多条记录。
- SELECT t1.*
- FROM table1 t1
- LEFT JOIN table2 t2 ON t1.id = t2.tid
第一种方法我们发现还是有重复数据
- SELECT tmp.id, max(tmp.name) FROM (
- SELECT t1.*
- FROM table1 t1
- LEFT JOIN table2 t2 ON t1.id = t2.tid
- ) tmp group by tmp.id
- SELECT distinct tmp.id, tmp.name FROM (
- SELECT t1.*
- FROM table1 t1
- LEFT JOIN table2 t2 ON t1.id = t2.tid
- ) tmp
我们需要查询重复的行的总行数,可以进行如下操作:
- SELECT tmp.id, count(tmp.name) as count FROM (
- SELECT t1.*
- FROM table1 t1
- LEFT JOIN table2 t2 ON t1.id = t2.tid
- ) tmp group by tmp.id order by id asc
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。