2

我有 13 个具有相同结构的表:

id  switch_name area

每个表包含特定区域的不同 switch_name。例如,

table1:
id    switch_name area
56    xxxx        A
77    yyyy        A
table2:
id    switch_name area
89    zzzz        B
78    uuuu        B

我需要使用这些表来更新另一个表“结果”,其中包含 id 并等待填充区域值。

所以我会做这个命令:

UPDATE results JOIN table1 ON results.switch_id = table1.id SET results.area = table1.area

这适用于一张桌子,但我想加入所有这 13 张桌子。我们以其中两个为例,我可以这样写查询:

 UPDATE results JOIN table1 ON results.switch_id = table1.id JOIN table2 ON results.switch_id = table2.id SET results.area = table1.area, results.area = table2.area

或者

UPDATE results JOIN table1 ON results.switch_id = table1.id SET results.area = table1.area JOIN table2 ON results.switch_id = table2.id SET results.area = table2.area

非常感谢

4

1 回答 1

2

如果所有tableN表具有相同的结构但不同的内容,UNION ALL则它们都在一个子查询中并与之连接。

UPDATE 
  results
  JOIN (
    SELECT id, switch_name, area FROM table1
    UNION ALL 
    SELECT id, switch_name, area FROM table2
    UNION ALL
    ..
    ..
    SELECT id, switch_name, area FROM table13
  ) alltogether ON results.switch_id = alltogether.id
SET results.area = alltogether.area
WHERE <conditions for update>

从长远来看,如果这些表都相似但包含同一数据集的不同子集,则它们可能应该合并到一个表中,该表具有区分其来源的列。

使用以下内容将它们合并到一个表中:

INSERT INTO new_combined_table 
  (id, switch_name, area, source)
  SELECT id, switch_name, area, 't1' AS source FROM table1
  UNION ALL
  SELECT id, switch_name, area, 't2' AS source FROM table2
  UNION ALL
  SELECT id, switch_name, area, 't3' AS source FROM table3
  ..
  ..
  UNION ALL 
  SELECT id, switch_name, area, 't13' AS source FROM table13
于 2012-05-14T14:31:48.787 回答