简体   繁体   English

从一个表复制到另一个具有相同列数和名称的表

[英]copy from one table to another with the same column count and name

I have the following two tables... 我有以下两个表...

Table1
colA    colB    colC    
1       a       w    
2       b       w    
3       c       s        
4       b       g    
5       n         


Table2
colA    colB    colC    
1       w       f    
2       w       r    
3       s       g    

I want to copy from table1 to table2 using UPDATE query, the problem I have is I have to SET all column name in which I have 100 column for each table, But I have the same column count and name too. 我想使用UPDATE查询从table1复制到table2,我遇到的问题是我必须设置所有列名,其中每个表都有100列,但是列数和名称也相同。

what would be easy way to run query UPDATE in php? 什么是在php中运行查询更新的简便方法?

is there some foreach thing out there might be... 是否有一些foreach事情可能存在...

Here is what I have now... 这就是我现在所拥有的...

public function update($id){
            try {
                UPDATE table1 b 
                INNER JOIN connect c 
                ON c.ID = b.ID 
                INNER JOIN table2 a 
                ON a.ID_a = c.ID_a 
                SET b.colA = a.colA,
                b.colB = a.colB,
                b.colC = a.colC
                .
                .
                .
                .
                . coontinue here all column name..
                .
                .
                WHERE a.ID_a = '".$id."' ";
             } catch(PDOException $e) {
                 $e->getMessage();
            }
            return false;
        }

some idea please? 有什么想法吗?

You don't need to do it via UPDATE syntax. 您不需要通过UPDATE语法执行此操作。 You can use INSERT..SELECT : 您可以使用INSERT..SELECT

INSERT INTO `table2` SELECT * FROM `table1`

this will works if you have exactly same structure in both tables. 如果两个表中的结构完全相同,这将起作用。 If not, you have to write column names (and map columns from first table to the second). 如果不是,则必须编写列名称(并将列从第一个表映射到第二个表)。

If you wand to replace corresponding values, then you should first delete present values: 如果要替换相应的值,则应首先删除当前值:

DELETE FROM `table2` WHERE `colA` IN (SELECT `colA` FROM `table1`)

if you want to update data in first table use values in other table you can use next statement 如果要更新第一个表中的数据,请使用其他表中的值,则可以使用next语句

UPDATE table_name AS t1 
SET t1.field_name = (SELECT field_name FROM other_table AS t2 WHERE t1.field=t2.field)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM