表格去重是我们经常会遇到的问题,怎么才能有效的根据数据信息去重:
1、数据表中存在索引列即ID(可以直接添加列)
2、多列数据相同使用group By筛选
3、存储过程去重表格数据
CREATE DEFINER=`root`@`localhost` PROCEDURE `uniq_table`()BEGINCREATE TABLE tmp SELECT MAX(index) as inde FROM yday GROUP BY userid,name;CREATE TABLE tmp2 SELECT old_table.* FROM old_table,tmp WHERE old_table.index= tmp.index;#删除旧表格DROP TABLE old_table;#表格重命名RENAME TABLE tmp2 TO new_table;#删除临时表DROP TABLE IF EXISTS tmp;#为新的去重表格添加自增序列alter table new_table MODIFY inde int(10) not null auto_increment first ,add primary key(index);END
group By和 having的使用
1、运算顺序:先group By 分组,后having 条件判断
2、having使用原因:WHERE 关键字无法与合计函数一起使用
#嵌套条件查询(注意临时表名‘a’)select count(*) from ( select userid from new_table group by userid having count(name) = 2 ) a;
添加列,删除列等
#查看表的字段信息:desc 表名;#查看表的所有信息:show create table 表名;#添加主键约束:alter table 表名 add constraint 主键 (形如:PK_表名) primary key 表名(主键字段);#添加外键约束:alter table 从表 add constraint 外键(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);#删除主键约束:alter table 表名 drop primary key;#删除外键约束:alter table 表名 drop foreign key 外键(区分大小写);#修改表名:alter table t_book rename to bbb;#添加列:alter table 表名 add column 列名 varchar(30);#删除列:alter table 表名 drop column 列名;#修改列名: alter table bbb change nnnnn hh int;#修改列属性:alter table t_book modify name varchar(22);