修改某一字段时,如果没有指定where主键,会有报错,解决方式如下:
SET SQL_SAFE_UPDATES=0;
删除重复数据 :
DELETE FROM country_code
WHERE
country_code NOT IN (SELECT
*
FROM
(select max(country_code) from country_code group by country_name )as tmp
);
根据一个表的数据,更新另一个表的数据 :
UPDATE event_insert as a,country_code as b
SET
a.country_code = b.country_code
WHERE
a.event_country_zh = b.country_name;
修改自增初始值:
ALTER TABLE tableName auto_increment=number ;
根据一个表的数据,插入到另一个表中:
insert into event_attack_target_style (event_attack_target_style.event_attack_target_style_name) select DISTINCT event.event_attack_target_style from event;
如果两表字段相同,则可以直接这样用:
insert into table_a select * from table_b
如果两表字段不同,a表需要b中的某几个字段即可,则可以如下使用:
insert into table_a(field_a1,field_a2,field_a3) select field_b1,field_b2,field_b3) from table_b
以上语句前提条件是每个字段对应的字段类型相同或可以自动转换。
或者使用union、union all
insert into test (cf1, c18)
( select 001, 0011 from dual where not exists( select cf1, c18 from test where cf1 = 001 and c18 = 0011 ) )
UNION
( select 001, 0011 from dual where not exists( select cf1, c18 from test where cf1 = 001 and c18 = 0011 ) )
区别是union可以排序和去重,union不可以
查找出一个表中的所有重复的记录 :
select user_name,count(*) as count from user_table group by user_name having count>1;
Mysql update 语句令某字段值等于原值加上一个字符串:
MySQL连贯字符串不能利用加号(+),而利用concat。比方在aa表的name字段前加字符'x',利用:update aa set name=concat('x',name)
Mysql DELETE语句删除group表中,属于group表但不属于perpetrator表的数据:NOT IN:
DELETE FROM `mini_anti`.group WHERE INGROUP!="" and INGROUP NOT IN(select groupid from perpetrator) ;
修改表字段:将test库中的test表,字段name的字段类型由varchar(255)修改为
ALTER TABLE `test`.`test`
CHANGE COLUMN `name` `name` LONGTEXT NULL DEFAULT NULL ;
mysql从csv格式导入:
load data local infile "/home/test.csv" into table user fields terminated by ',';
mysql导出csv格式:
select * from student as t1 inner join course as t2 on t1.userid=t2.userid into outfile '/var/lib/mysql-files/usercourse.csv' fields terminated by ',' lines terminated by '\n';
mysql 形容 like in :把所有姓刘、张、王的人取出来
select * from user where name REGEXP '刘|张|王';
只复制表结构到新表:
CREATE TABLE 新表 SELECT * FROM 旧表 where 1=0
复制表结构及数据到新表:
CREATE TABLE 新表 SELECT * FROM 旧表
把指定数据行排在前面:把user_id为7的放在第一个
SELECT * FROM user ORDER BY user_id!=7