表結構
CREATE TABLE `goods` (
`id` int NOT NULL ,
`name` varchar(25) ,
`updateat` datetime
)
現在表中有這樣一段資料

當我想插入一條新資料時,(1,'new','2021-12-18 12:00:00')首先判斷表中是否有與要插入的資料相同的資料(更新時間除外),然后比較更新時間,保留最新的那條資料。
我想知道如何使用sql來實作這個功能。
uj5u.com熱心網友回復:
首先將主鍵添加到您的表中:
CREATE TABLE goods (
id int NOT NULL ,
name varchar(25) ,
updateat datetime,
PRIMARY KEY (id, name)
)
然后使用ON DUPLICATE KEY UPDATE:
insert into goods values (1, 'john', '2021-01-02');
insert into goods (id, name, updateat)
values (1, 'john', '2021-01-03')
ON DUPLICATE KEY UPDATE
updateat = greatest('2021-01-03',
(select updateat from (select * from goods as g) as g where id = 1))
小提琴
uj5u.com熱心網友回復:
Mysql 使用INSERT ON...DUPLICATE而不是合并。此陳述句允許您根據識別重復條目時的檢查對您的案例進行修改和更新。可以使用主鍵或唯一索引來識別重復條目。下面的演示和作業資料庫小提琴根據您的標準給出了一個例子。
- 使用唯一索引來識別重復條目
- 使用
INSERT ON...DUPLICATE與VALUES(用于識別當前插入值)和一個殼體表達以確定哪個updatedat日期是較新的。
CREATE TABLE `goods` ( `id` int NOT NULL , `name` varchar(25) , `updateat` datetime );
?
-- use a unique index if you are interested in ensuring a subset of columns are unique and -- these columns do not meet the criteria to be a primary/composite key based on your database design create unique index uk_id_name on goods(id,name);?
insert into goods values (1,'new','2021-12-18 12:00:00');
?
-- this should fail because of the duplicate unique index insert into goods values (1,'new','2021-12-18 12:00:00');密鑰“uk_id_name”的重復條目“1-new”
select * from goods;
身份證 | 姓名 | 更新時間 -: | :--- | :------------------ 1 | 新 | 2021-12-18 12:00:00
insert into goods values (1,'new','2021-12-18 12:00:01') on duplicate key update updateat= CASE WHEN updateat > VALUES(updateat) THEN updateat ELSE VALUES(updateat) END;
?
select * from goods;身份證 | 姓名 | 更新時間 -: | :--- | :------------------ 1 | 新 | 2021-12-18 12:00:01
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385464.html
