如何合并两个MySQL表

时间:2012-11-20 06:25:37

标签: mysql sql merge

区域

view    state         region
EB1     TamilNadu     Chennai-North
EB2     AndhraPradesh     Guntur

国家/地区

view    code    country   state
EB1     +91     India     TamilNadu
EB2     +91     India     AndhraPradesh
EB3     +91     India     Delhi
EB4     +91     India     Delhi

我想根据region表中不存在的视图合并这些表。

结果表必须如下所示:

view    code    country   state
EB3     +91     India     Delhi
EB4     +91     India     Delhi

EB1中存在EB2region

2 个答案:

答案 0 :(得分:1)

您需要使用LEFT JOIN。您需要表region上不存在的值。所以你需要使用WHERE r.view IS NULL。您的整个查询应该是:

   SELECT c.*
     FROM country c
LEFT JOIN region r
       ON c.view = r.view
    WHERE r.view IS NULL

See this SQLFiddle

<强>更新

如果要创建名为result的新表,并希望在该表中添加这些值,可以使用以下查询:

创建新表:

CREATE TABLE result
    (`view` varchar(3), `code` varchar(4)
     , `country` varchar(5), `state` varchar(13))
;

在该表上插入值:

INSERT INTO result (`view`, `code`, `country`, `state`)
      SELECT c.view, c.code, c.country, c.state
        FROM country c
   LEFT JOIN region r
          ON c.view = r.view
       WHERE r.view IS NULL

See this SQLFiddle

答案 1 :(得分:0)

如果要创建新表:

CREATE TABLE new_table (
  SELECT * FROM country
  WHERE view NOT IN (
    SELECT view FROM region
  )
)

或者如果您只想创建视图,请使用相同的查询,将CREATE TABLE替换为CREATE VIEW AS