用替换合并两个sql表?

svmlkihl  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(520)

长话短说,我需要能够结合两个表(一个是前一个有点重叠的延续)。然后我需要将一列设置为主键,这意味着没有重复项。当我尝试在sqlmanagementstudio中使用导入向导并将一个表导入另一个表时,它只是将一个表中的所有数据添加到下一个表中。我需要找出某种方法或sql命令,将新表中的所有数据导入旧表,并用新表中的数据替换任何现有的重复数据。
这样想,我有两个表,其中包含以下数据:

People_Old table
+------+--------+
| Name | Color  |
+------+--------+
| Mary | Blue   |
| Katy | Yellow |
| Jim  | Green  |
| John | Red    |
+------+--------+

People table
+------+--------+
| Name | Color  |
+------+--------+
| Jim  | Silver |
| John | Brown  |
| Greg | Purple |
| Liz  | Pink   |
+------+--------+

假设“name”列是主键,我想将较新的“people”表中的数据添加到较旧的“people\u old”表中,但是替换重叠的数据,这样就不会有重复的数据。在本例中,我希望最后的“people\u old”表是:

+------+--------+
| Name | Color  |
+------+--------+
| Mary | Blue   |
| Katy | Yellow |
| Jim  | Silver |
| John | Brown  |
| Greg | Purple |
| Liz  | Pink   |
+------+--------+
yiytaume

yiytaume1#

DROP TABLE IF EXISTS old;

CREATE TABLE old
(Name VARCHAR(12) NOT NULL PRIMARY KEY
,Color  VARCHAR(12) NOT NULL
);

INSERT INTO old VALUES
('Mary','Blue'),
('Katy','Yellow'),
('Jim','Green'),
('John','Red');

DROP TABLE IF EXISTS new;

CREATE TABLE new
(Name VARCHAR(12) NOT NULL PRIMARY KEY
,Color  VARCHAR(12) NOT NULL
);

INSERT INTO new VALUES
('Jim' ,'Silver'),
('John','Brown'),
('Greg','Purple'),
('Liz' ,'Pink');

SELECT * FROM old;
+------+--------+
| Name | Color  |
+------+--------+
| Mary | Blue   |
| Katy | Yellow |
| Jim  | Green  |
| John | Red    |
+------+--------+

SELECT * FROM new;
+------+--------+
| Name | Color  |
+------+--------+
| Jim  | Silver |
| John | Brown  |
| Greg | Purple |
| Liz  | Pink   |
+------+--------+

INSERT INTO old 
SELECT name
     , color 
  FROM new 
    ON DUPLICATE KEY UPDATE old.color = new.color;

SELECT * FROM old;
+------+--------+
| Name | Color  |
+------+--------+
| Mary | Blue   |
| Katy | Yellow |
| Jim  | Silver |
| John | Brown  |
| Greg | Purple |
| Liz  | Pink   |
+------+--------+
6 rows in set (0.00 sec)
slsn1g29

slsn1g292#

使用 REPLACE 声明,类似于:

replace into people_old select * from people;

相关问题