【问题标题】:How to copy data from one table to another based on ids present in third table in MySQL?如何根据 MySQL 中第三个表中存在的 id 将数据从一个表复制到另一个表?
【发布时间】:2016-07-01 22:29:05
【问题描述】:

我有三张类似的桌子

表 1

这是一个与 Table2 具有相同列的空白表。

表2

它包含了表1中需要复制的实际数据。

id   cola   colb   colc cold
1     hd     dj    dj    dh
2     hf     uy    ug    se
...

Table3

在将数据从 Table2 复制到 Table1 之前,首先我需要验证 id 是否存在于 Table3 中。换句话说,我只想将 Table2 中的行复制到 Table1 中,其 id 存在于 Table3 中。

id   col1    col2
1     xy      zz
2     ys      sh

还有一个东西Table2 & Table3 包含50万行,所以查询一定是可行的。

【问题讨论】:

  • 你可以看看我三年前问的问题stackoverflow.com/questions/10351998/…
  • 你有没有尝试过?
  • 这是非常基本的东西。从 MySQL 的初学者教程开始。
  • @Nitish 我已经尝试了以下所有已回答的查询,但这些都需要大量时间和资源。我正在以查询或工具等形式寻找可行的解决方案。
  • @user2350535:你需要注意你的语言。请拨打tour 并阅读How to Ask 以了解我们对这里问题的期望。请注意,我们不提供从头开始的编码服务。请告诉我们您已经尝试过什么,它是如何失败的,我们或许可以提供帮助。

标签: php mysql sql phpmyadmin wamp


【解决方案1】:

有人将此作为重复的问题 然而答案是

insert into Table1 
select * from Table2 where Table1.id=Table2.id

【讨论】:

    【解决方案2】:

    使用子查询的选项 1:

    insert into Table1 
    select * from Table2 where id in (select id from Table3)
    

    使用 INNER JOIN 的选项 2:

    insert into Table1 
    select * from Table2 INNER JOIN Table3 USING(id);
    

    【讨论】:

    • 更新了帖子,添加了一种使用 INNER JOIN 的新方法。
    【解决方案3】:
     insert into Table1 
    select * from Table2 where id in (select id from Table3)
    

    如果 table1 和 table2 中的列数相同,则上述查询将起作用

    其他

        insert into Table1 (column1,column2,.....)
    select column1,column2...  from Table2 where id in (select id from Table3)
    

    【讨论】:

      【解决方案4】:

      使用连接。它更快。

      insert into table1 (id, cola, colb, colc, cold)
      select t2.id,t2.cola,t2.colb,t2.colc,t2.cold 
        from table2 t2 
      left join 
             table3 t3 
        on t2.id=t3.id
      where t3.id is null
      

      【讨论】:

        【解决方案5】:

        您可以使用EXISTS

        查询

        insert into Table1(id, cola, colb, colc, cold)
        select id, cola, colb, colc, cold
        from Table2 t
        where exists(
            select * from Table3
            where id = t.id
        );
        

        JOIN

        insert into id, cola, colb, colc, cold
        select t1.id, t1.cola, t1.colb, t1.colc, t1.cold
        from Table2 t1
        join Table3 t2
        on t1.id = t2.id;
        

        【讨论】:

          猜你喜欢
          • 2011-11-20
          • 2012-03-23
          • 2011-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-20
          相关资源
          最近更新 更多