Mysql小技巧

2024-06-26 20:35:02 浏览数 (1)

1、ON DUPLICATE KEY UPDATE:如果key重复了违反唯一约束,更新。

INSERT INTO table (id, column1, column2)

VALUES (1, 'A', 'X'), (2, 'A', '2')

ON DUPLICATE KEY UPDATE column1='A', column2='X';

2、INSERT IGNORE:如果id冲突了,则忽略这条数据

INSERT IGNORE INTO table (id, column1, column2)

VALUES (1, 'A', 'X');

3、REPLACE INTO: 如果id冲突了,则删除老数据,用这个新数据

REPLACE INTO table (id, column1, column2)

VALUES (1, 'A', 'X');

4、SELECT ... FOR UPDATE:需要手动创建事务,并commit;

START TRANSACTION;

SELECT * FROM table WHERE id = 1 FOR UPDATE;

-- 进行一些操作

COMMIT;

5、LOAD DATA INFILE:这个不适用于添加手动的数据,一个数据缺失导致所有的都失败。这个适用于手动进行数据同步。

-- 导出基础参数

select * into outfile '/data/mysql/3306/tmp/employees.txt'

character set utf8mb4

fields terminated by ','

enclosed by '"'

lines terminated by 'n'

from employees.employees1 limit 10;

-- 导入基础参数

load data infile '/data/mysql/3306/tmp/employees.txt'

replace into table demo.emp2

character set utf8mb4

fields terminated by ','

enclosed by '"'

lines terminated by 'n'

(field1, field2, field3,,,,)

0 人点赞