mysql常用操作记录
1,删除多个重复字段的数据
创建表
CREATE TABLE `TEST` (
`ID` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`CODE` VARCHAR(32) DEFAULT NULL,
`NAME` VARCHAR(32) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=INNODB AUTO_INCREMENT=20 DEFAULT CHARSET=UTF8;
插入数据
TRUNCATE TABLE `TEST`;
INSERT INTO `TEST`(`ID`,`CODE`,`NAME`) VALUES
(1,'C1','N1'),
(2,'C2','N2'),
(3,'C2','N2'),
(4,'C2','N21'),
(5,'C2','N21'),
(6,'C3','N3'),
(7,'C3','N3'),
(8,'C3','N3'),
(9,'C3','N31'),
(10,'C3','N31'),
(11,'C3','N31'),
(12,'C4','N4'),
(13,'C4','N4'),
(14,'C4','N4'),
(15,'C4','N4'),
(16,'C4','N41'),
(17,'C4','N41'),
(18,'C4','N41'),
(19,'C4','N41');
删除
DELETE FROM `TEST` WHERE `ID` IN(
SELECT * FROM(
SELECT `ID` FROM `TEST` WHERE (`CODE`,`NAME`) IN (
SELECT `CODE`,`NAME` FROM `TEST` GROUP BY `CODE`,`NAME` HAVING COUNT(*)> 1
)
AND `ID` NOT IN(
SELECT MIN(`ID`)FROM `TEST` GROUP BY `CODE`,`NAME` HAVING COUNT(*)> 1
)
) T
);
2.查看和修改编码
A. 查看数据库的字符集方式
– database_name 为数据库名称
SHOW CREATE DATABASE database_name;
B. 查看表的字符集方式
– table_name为表的名称
SHOW CREATE TABLE table_name;
C. 查看字段的字符集方式
– table_name为表名称
SHOW FULL COLUMNS FROM table_name;
修改数据库、表和字段的字符集方式如下
A. 修改数据库的字符集方式
– database_name 为数据库名称
– utf8为目标字符编码
ALTER DATABSE database_name DEFAULT CHARACTER SET utf8;
B. 修改表的字符集方式
– table_name为表的名称
– utf8为目标字符编码
ALTER TABLE table_name DEFAULT CHARACTER SET utf8;
C. 修改字段的字符集方式
– table_name为表的名称
– column_name为字段名称
– varchar(20)为字段的类型
– utf8为目标字符集
ALTER TABLE table_name CHANGE column_name column_name VARCHAR(20) CHARACTER SET utf8;
D. 同时修改表和表中所有字符类型的字段字符集方式
– 例子:alter table user2 convert to character set utf8 collate utf8_general_ci;
ALTER TABLE tbl_name CONVERT TO CHARACTER SET character_name [COLLATE ...]