在MySQL中进行重复密钥更新
假设我有两张桌子在MySQL中进行重复密钥更新,mysql,sql,subquery,sql-insert,store,Mysql,Sql,Subquery,Sql Insert,Store,假设我有两张桌子 CREATE TABLE shipping(id int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, origin INT(10), order_id int(10), createdAt date NOT NULL, product_id varchar(100) NOT NULL, amount decimal(10,0)); CREATE TABLE reprint (id int(10) NOT NULL PRIMARY KEY
CREATE TABLE shipping(id int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, origin INT(10),
order_id int(10), createdAt date NOT NULL, product_id varchar(100) NOT NULL,
amount decimal(10,0));
CREATE TABLE reprint (id int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
product_id int(50), reprintAt varchar(255), status tinyint(4));
INSERT INTO shipping (origin, order_id, createdAt, product_id, amount)
VALUES (1, 11, NOW(), 234, 2000),
(1, 11, NOW(), 235, 3000),
(1, 11, NOW(), 236, 4000),
(2, 12, NOW(), 236, 3000),
(2, 12, NOW(), 235, 2100),
(3, 13, NOW(), 236, 2200),
(3, 13, NOW(), 239, 3400),
(4, 14, NOW(), 237, 2300),
(4, 14, NOW(), 233, 4000);
INSERT INTO reprint (product_id, reprintAt, status)
VALUES (234, NOW() + INTERVAL 1 DAY, 1),
(235, NOW() + INTERVAL 2 DAY, 1),
(236, NOW(), 1),
(237, NOW(), 1),
(238, NOW(), 1),
(239, NOW(), 1),
(240, NOW(), 1),
(233, NOW(), 1);
表装运
身份证件
起源
订单号
创建数据
产品标识
数量
1.
1.
11
2020-12-22
234
2000
2.
1.
11
2020-12-22
235
3000
3.
1.
11
2020-12-22
236
4000
4.
2.
12
2020-12-22
236
3000
5.
2.
12
2020-12-22
235
2100
6.
3.
13
2020-12-22
236
2200
7.
3.
13
2020-12-22
239
3400
8.
4.
14
2020-12-22
237
2300
9
4.
14
2020-12-22
233
4000
如果我没有弄错,您可以使用
不存在:
insert into shipping (origin, order_id, createdat, product_id, amount)
select id, 16, reprintat, product_id, 4000
from reprint r
where not exists (select 1 from shipping s where s.product_id = r.product_id)
这将为目标中尚未存在产品的每一行重新打印创建一个新的发货行,且数量和订单id不变
我认为在这种情况下,重复键上的没有意义,因为产品不是唯一的列。如果我没有弄错,您可以使用不存在
:
insert into shipping (origin, order_id, createdat, product_id, amount)
select id, 16, reprintat, product_id, 4000
from reprint r
where not exists (select 1 from shipping s where s.product_id = r.product_id)
这将为目标中尚未存在产品的每一行重新打印创建一个新的发货行,且数量和订单id不变
我认为重复键上的在这种情况下没有意义,因为产品不是唯一的列。我认为您的问题可以通过简单的SQL查询解决,使用不存在语句:
INSERT INTO shipping (origin, order_id, createdAt, product_id, amount)
SELECT reprint.id, 16, reprint.reprintAt, reprint.product_id, 4000
FROM reprint
WHERE NOT EXISTS (
SELECT product_id FROM shipping WHERE shipping.product_id = reprint.product_id
);
这里的我认为您的问题可以通过简单的SQL查询解决,使用NOT EXISTS
语句:
INSERT INTO shipping (origin, order_id, createdAt, product_id, amount)
SELECT reprint.id, 16, reprint.reprintAt, reprint.product_id, 4000
FROM reprint
WHERE NOT EXISTS (
SELECT product_id FROM shipping WHERE shipping.product_id = reprint.product_id
);
这里的您只能在存储例程中声明变量。您只能在存储例程中声明变量。对不起,先生,这只是我想到的一件事,在重复键上使用和不存在的最佳时间
查询?对不起,先生,这只是我想到的一件事,在重复键上使用和不存在的最佳时间是什么时候?