在MySQL数据库中,如果在insert语句后面带上ON DUPLICATE KEY UPDATE 子句,而要插入的行与
表中现有记录的惟一索引或主键中产生重复值,那么就会发生旧行的更新;如果插入的行数据与现有表
中记录的唯一索引或者主键不重复,则执行新记录插入操作。
简而言之:数据存在则更新,无则创建
INSERT INTO 表名
(字段名1, 字段名2 )
VALUES
(字段值1, 字段值2)
ON DUPLICATE KEY UPDATE
字段名1 = VALUES(字段名1),
字段名2 = VALUES(字段名2)
注意事项:
假如我们有这个app表,现在把其中一列name设置为unique
ALTER TABLE public.applications ADD CONSTRAINT applications_un UNIQUE (name);
然后我们去写代码
这个语句: 当数据存在时,什么都不做(DO NOTING)
const insertApp = await client.query(`INSERT INTO applications
(app_name, details )
VALUES
('${appName}', '${appDetail}')
ON CONFLICT ON CONSTRAINT applications_un
DO NOTHING;
`);
下面的语句有一样的效果,区别在于使用的是 name 字段,而不是约束的名字
INSERT INTO customers (app_name, details)
VALUES
(
'AAA',
'BBBBBB'
)
ON CONFLICT (name)
DO NOTHING;
INSERT INTO customers (app_name, details)
VALUES
(
'AAA',
'BBBBBB'
)
ON CONFLICT (name)
DO
UPDATE
SET email = 'CCCCCCCC';
upsert
使用相同变量,多次执行这段逻辑,我们会发现只创建了一条,所以是成功的~~~
举个栗子:从users表里查询details信息和user_name信息包含字母’xiaojin’
select * from users where lower(details) like '%xiaojin%' or lower(user_name) like '%xiaojin%'
举个栗子: 从users表查询type类型为Admin 或者 Super Admin
select * from users where "type" in ('Admin', 'Super Admin')
举个栗子: 我想查询users表created_at字段从2023-08-01 00:00:00.000 到2023-08-10 00:00:00.000范围内的数据
select * from users where created_at between '2023-08-01 00:00:00.000' and '2023-08-10 00:00:00.000'
ALTER TABLE public.users ADD id serial4 NOT NULL;
ALTER TABLE public.users ADD "user_name" varchar(255) NULL;
ALTER TABLE public.users ADD description varchar(255) NULL;
ALTER TABLE public.users ADD "type" varchar(255) NULL;
ALTER TABLE public.users ADD created_at timestamp(6) NULL;
ALTER TABLE public.users ADD updated_at timestamp(6) NULL;
ALTER TABLE public.users ADD created_by varchar(255) NULL;
ALTER TABLE public.users ADD updated_by varchar(255) NULL;
DROP DATABASE IF EXISTS tangdoudou;
CREATE DATABASE tangdoudou;
USE tangdoudou;
CREATE TABLE student (
sid INT, # integer 整形
name VARCHAR(8), # variable character可变字符
sex VARCHAR(1), # m->男 f->女
score INT
);
INSERT INTO student VALUES('1','tom','F','95');
SELECT * FROM student;
UPDATE student SET name='lucy',score='100' WHERE sid='2';
DELETE FROM student WHERE sid='3';
DROP DATABASE IF EXISTS tangdoudou;
CREATE DATABASE tangdoudou;
DROP DATABASE IF EXISTS tangdoudou;
USE tangdoudou;
DROP TABLE IF EXISTS student;
CREATE TABLE student (
sid INT, # integer 整形
name VARCHAR(8), # variable character可变字符
sex VARCHAR(1),# m->男 f->女
score INT
);
INSERT INTO student VALUES('1','tom','m','85');
INSERT INTO student VALUES('2','kate','f','92');
INSERT INTO student VALUES('3','king','m','74');
UPDATE student SET name='lucy' WHERE sid='2';
UPDATE student SET score='100' WHERE sid='2';
DELETE FROM student WHERE sid='3';
SELECT * FROM student;
欢迎大家指出文章需要改正之处~
学无止境,合作共赢