将两个SQL表与替换组合在一起?

时间:2018-01-05 17:08:19

标签: mysql sql database datatable

长话短说,我需要能够将两个表组合在一起(一个是前一个表的延续,有一点重叠)。然后我需要将一列设置为主键,这意味着没有重复。当我尝试在SQL Management Studio中使用导入向导并将一个表导入另一个表时,它只是将一个表中的所有数据添加到下一个表中。我需要弄清楚将新表中的所有数据导入旧表的某种方式或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   |
+------+--------+

假设"姓名"列被认为是主键,我想添加来自较新的"人物"表格进入旧的" People_Old"表,但替换重叠数据,以便没有重复。在这个例子中,我想要最终的" People_Old"表格为:

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

2 个答案:

答案 0 :(得分:0)

使用string语句,例如:

REPLACE

答案 1 :(得分:0)

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)