主要涉及:join 、join 更新、group by having 数据查重/去重
1 inner join、left join、right join、full join(mysql 不支持)、cross join
这是在网上找到的非常好的一篇博文,图解 join 语句:
coding horror-a visual explanation of sql joins
下图可以很清楚的明白,join 的数据选取范围
[][1]
[1]: http://7xs09x.com1.z0.glb.clouddn.com/160725-imooc-mysql-development-skills-notes-001.png
2 更新使用过滤条件中包括本身的表
更新 t1 t2 表中 col_a 重复的字段
update t1
set col_a = 'hi'
where t1.col_a in (
select b.col_a
from t1 a inner join t2 b on
a.col_a = b.col_a
)
;
error:1093
可转换为:
update t1 aa join(
select b.col_a
from t1 a inner join t2 b on
a.col_a = b.col_a
)bb on aa.col_a= bb.col_a
set col_a = 'hi'
;
3 查询重复数据、删除重复数据
利用 group by 和 having 查询重复数据
select col_a, count(*)
from t1
group by col_a having count(*) > 1
;
删除重复数据,对于相同数据保留 id 最大的
delete a
from t1 a join (
select col_a,count(*),max(id) as id
from t1
group by col_a having count(*) > 1
)b on a.col_a = b.col_a
where a.id < b.id
;
感谢阅读此文,希望能帮助到大家,谢谢大家对本站的支持!
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!