MySQL:将特定列从一个数据库复制到另一个数据库,使主键保持不变

时间:2016-06-03 19:43:21

标签: mysql

我有两个数据库,开发和生产。它们都具有相同的表和列结构。

我需要将一些生产数据移动到dev中,保留相同的主键ID但使用WHERE子句。

    UPDATE 
      dev.tableA, 
      prod.tableA
    SET 
      dev.tableA.title = prod.tableA.title,
      dev.tableA.url_title = prod.tableA.url_title,
      dev.tableA.status = prod.tableA.status,
      dev.tableA.edit_date = prod.tableA.edit_date
    WHERE 
      dev.tableA.entry_id = prod.tableA.entry_id
      AND prod.tableA.channel_id = 7

当我运行上面的查询时,我得到一个0行受影响的消息。

我也尝试了这个声明,但是又影响了0行。

        UPDATE 
            dev.tableA dt
            INNER JOIN 
                prod.tableA tt
        ON 
            tt.entry_id = dt.entry_id
            SET 
                dt.title = tt.title,
                dt.url_title = tt.url_title,
            dt.status = tt.status,
            dt.edit_date = tt.edit_date
          WHERE 
            tt.channel_id = 7;

2 个答案:

答案 0 :(得分:0)

您的更新看起来很好,但如果值已经相同则会返回0; MySQL默认只告诉你实际更改的行。

虽然我会更像这样缩进:

UPDATE dev.tableA AS dt
   INNER JOIN prod.tableA AS tt
      ON tt.entry_id = dt.entry_id
SET dt.title = tt.title
   , dt.url_title = tt.url_title
   , dt.status = tt.status
   , dt.edit_date = tt.edit_date
WHERE tt.channel_id = 7
;

我通常会避免INSERT IGNOREREPLACE INTO次查询;我发现它们引起的问题多于它们的价值。代替...

INSERT INTO tableA (id, field1, field2, field3)
SELECT id, field1, field2, field3
FROM tableB AS b
WHERE tableB.id NOT IN (SELECT id FROM tableA)
;
-- OR (the below version may be faster) --
INSERT INTO tableA (id, field1, field2, field3)
SELECT b.id, b.field1, b.field2, b.field3
FROM tableB AS b
LEFT JOIN tableA AS a ON b.id = a.id
WHERE a.id IS NULL -- assuming id is not nullable
;

同样......

DELETE FROM tableA 
WHERE tableA.field1 NOT IN (SELECT field1 FROM tableB)
;
-- OR (the below version may be faster) --
DELETE a 
FROM tableA AS a LEFT JOIN tableB AS b ON a.id = b.id
WHERE b.id IS NULL
;

答案 1 :(得分:0)

您可以将INSERTON DUPLICATE KEY UPDATE子句一起使用。

INSERT INTO dev.tableA (entry_id, title, url_title, status, edit_date)
SELECT entry_id, title, url_title, status, edit_date
FROM prod.tableA
WHERE channel_id = 7
ON DUPLICATE KEY UPDATE 
    title = VALUES(title), url_title = VALUES(url_title),
    status = VALUES(status), edit_date = VALUES(edit_date)