最近看了一些关于Mysql优化方面的东西,想整理下来。
第一个是查询优化的
1、order by
2、group by
3、limit
4、index
5、删除表中的重复行
(一)删除表中的重复行,建立复合主键
先从表中的重复行建立复合索引来说:
table name prima
col1
aa1
aa1
aa1
aa2
aa3
aa3
aa3
需要建立复合主键(col1,col2,col3)
网上流传着很多版本的删除重复行的方法,但经历几天的研究终于找到一种适合于mysql的最简洁高效的建立主键的方法(灰常强悍):
alter ignore table prima add primary key (col1,col2,col3);
当然还有其他的解决办法:
方法一:
1、选出所有重复的列,并存入临时表中
2、将原表中于临时表相同的记录删除
3、建立复合主键 alter table prima add primary key (col1,col2,col3);
4、将临时表中的记录插入原表中
方法二:
1、增加一列自动增长的id.
2、删除重复数据,只保留一条记录.
delete from prima using (prima,(select distinct min(id) as id ,col1,col2,col3 from prima group by col1,col2,col3 having count(1)>1) as t2 )
where prima.col1=t2.col1 and prima.col2=t2.col2 and prima.col3=t2.col3 and prima.id > t2.id;
3、删除id字段 alter table prima drop id;
方法二来源:http://www.cnblogs.com/consatan/archive/2010/12/17/1909087.html
注:mysql 与Oracle、 MS Server在delete上有一点区别,在写法上的要求不一样,当要删除一个表中的某些数据的时候不能直接写成
delete from prima where (col1,col2,col3) in (select col1,col2,col3 from prima group by col1,col2,col3 having count(1)>1) 这个样子,会报锁表错。
猜测是delte 的时候表会被锁,不让读,而改为using 标准写法后是不是生成临时表?