我能够在Oracle和MSSQL中使用MERGE语句。现在我必须使用MYSQL。 MYSQL是否有类似的声明来合并数据。
假设我有两张桌子:
create table source
(
col1 bigint not null primary key auto_increment,
col2 varchar(100),
col3 varchar(50)
created datetime
)
create table destination
(
col1 bigint not null primary key auto_increment,
col2 varchar(100),
col3 varchar(50)
created datetime
)
现在我希望移动来自" source"的所有数据。到"目的地"。如果记录已存在于"目的地"按键我需要更新,否则我需要插入。
在MSSQL中我使用以下MERGE语句,类似可以在ORACLE中使用:
MERGE destination AS TARGET
USING(SELECT * FROM source WHERE col2 like '%GDA%') AS SOURCE
ON
(TARGET.col1 = SOURCE.col1)
WHEN MATCHED THEN
UPDATE SET TARGET.col2 = SOURCE.col2,
TARGET.col3 = SOURCE.col3
WHEN NOT MATCHED THEN
INSERT INTO
(col2,col3,created)
VALUES
(
SOURCE.col2,
SOURCE.col3,
GETDATE()
)OUTPUT $action INTO $tableAction;
WITH mergeCounts AS
(
SELECT COUNT(*) cnt,
MergeAction
FROM @tableAction
GROUP BY MergeAction
)
SELECT @Inserted = (SELECT ISNULL(cnt,0) FROM mergeCounts WHERE MergeAction = 'INSERT'),
@Updated = (SELECT ISNULL(cnt,0) FROM mergeCounts WHERE MergeAction = 'UPDATE'),
@Deleted = (SELECT ISNULL(cnt,0) FROM mergeCounts WHERE MergeAction = 'DELETE')
所以我在这里更新记录(如果存在)并插入新记录。在MERGE语句之后,我还可以计算插入了多少条记录,更新了......
是否可以在MYSQL中实现这样的实现?
答案 0 :(得分:1)
Mysql具有insert ... on duplicate key update ...
语法。像这样使用它:
insert into destination(col1, col2, col3, created)
select *
from source
on duplicate key update
col2 = values(col2),
col3 = values(col3),
created = values(created);
获取受影响的行数,然后运行select row_count()