【问题标题】:MySQL - Add a column to Temporary Tables from another TableMySQL - 从另一个表向临时表添加一列
【发布时间】:2018-02-23 12:48:48
【问题描述】:

我想知道您是否可以在不需要创建新表的情况下向临时表添加列

让我们假设以下表格

Table1     |    Table2     |    Table3     |
Id  Atype  |    Id  Btype  |    Id  Ctype  |
1   A1     |    1   B1     |    1   C1     |
2   A2     |    2   B2     |    2   C2     |
3   A3     |    3   B3     |    3   C3     |

首先我想创建一个临时表:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(id) )
AS (
  SELECT t1.id, t1.atype , t2.btype
  FROM table1 t1
  left join table2 t2 on t1.id = t2.id);

Result:
temp_table
Id  Atype  Btype
1   A1     B1
2   A2     B2
3   A3     B3

然后我想在临时表中添加 Ctype。 我怎样才能做到这一点? 我可以加入当前的临时表还是必须创建一个新的临时表?

我正在寻找的最终结果是 1 个临时表,如下所示:

Id  Atype  Btype  Ctype
1   A1     B1     C1
2   A2     B2     C2
3   A3     B3     C3

【问题讨论】:

    标签: mysql sql temp-tables


    【解决方案1】:

    你不能用另一个join吗?

    SELECT t1.id, t1.atype, t2.btype, t3.ctype
    FROM table1 t1 LEFT JOIN
         table2 t2 
         ON t1.id = t2.id LEFT JOIN
         table3 t3
         ON t1.id = t3.id
    

    如果你真的想修改现有的表,那么:

    alter table temp_table add ctype varchar(255);

    update temp_table tt join
           table3 t3
           on tt.id = t3.id
        set tt.ctype = t3.ctype;
    

    【讨论】:

    • 我同意 Gordon 的观点,但是如果您需要在临时表中添加一列,您应该可以使用 ALTER TABLE 来完成。
    • @RyanWilson 。 . .真的。但是为什么不直接创建您想要开始的临时表。
    • @GordonLinoff 我想将“许多”表连接在一起,当您每次加入两个或三个表时,这会更容易。但是,当我使用您推荐的语句时,我收到以下信息:错误代码:1175。您正在使用安全更新模式,并且您尝试更新没有 WHERE 使用 KEY 列的表要禁用安全模式,请切换首选项中的选项-> SQL 编辑器并重新连接。
    • @Gizazas 。 . .不,一次加入 2 个或 3 个并不“容易”。只需编写您想要的查询并将结果保存在临时表中。
    • @GordonLinoff 我同意你提出的两点,我只是想我会把 ALTER TABLE 命令扔在那里,因为他似乎想从问题中知道这一点。
    【解决方案2】:

    您可以在创建插件时执行第三个 join()

      CREATE TEMPORARY TABLE IF NOT EXISTS 
        temp_table ( INDEX(id) )
      AS (
        SELECT t1.id, t1.atype , t2.btype, t3.Ctype
        FROM table1 t1
        left join table2 t2 on t1.id = t2.id
        left join table3 t3 on t1.id = t3.id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      相关资源
      最近更新 更多