插入表2中列所在的另一个表中

时间:2013-06-04 09:04:57

标签: php sql-server

我想将表1的值插入表2,其中表2中的列存在于表1中。有关更多参考,请参阅此表:

表1

+----------+----------+----------+
|  col_1   |  col_2   |   col_3  |
+----------+----------+----------+
| col_val  | col_val  | col_val  |
| col_val  | col_val  | col_val  |
| col_val  | col_val  | col_val  |
| col_val  | col_val  | col_val  |
+----------+----------+----------+

表2

+----------+----------+----------+----------+----------+
|  col_1   |  col_2   |   col_3  |  col_4   |  col_5   |
+----------+----------+----------+----------+----------+
| col_val  | col_val  | col_val  |          |          |
| col_val  | col_val  | col_val  |          |          |
| col_val  | col_val  | col_val  |          |          |
| col_val  | col_val  | col_val  |          |          |
+----------+----------+----------+----------+----------+

如果表1中的列不存在于表1中,则会插入空值。

提前致谢!

2 个答案:

答案 0 :(得分:0)

您可以设置col 4&的默认值。 col 5为NULL然后运行此查询:

INSERT INTO table1 (col1, col2, col3)
SELECT col1, col2, col3 FROM table2;

它应该可以工作,但你必须明确指定两个表之间的共同列。

答案 1 :(得分:0)

试试这个:

<?php
$con=mysqli_connect("yourhost", "username", "password", "your_db");
if(!$con){
    //error    
}

$query1="select * from table1 limit 1";
$query2="select * from table2 limit 1";

$result1=mysqli_query($con, $query1);
$result2=mysqli_query($con, $query2);


if(!$result2 || !$result1){
    //query error    
}

$table1_columns=array_keys(mysqli_fetch_assoc($result1));
$table2_columns=array_keys(mysqli_fetch_assoc($result2));

$intesection=array_intersect($table1_columns, $table2_columns);


if(is_array($intesection) && !empty($intesection)){
    $query="insert into table2 (";
    foreach($intesection as $column){
        $query.=" $column,";
    }

    $query=substr($query, 1,-1); //to remove the last comma
    $query.=") select ";

    foreach($intesection as $column){
        $query.=" $column,";
    }
    $query=substr($query, 1,-1); //to remove the last comma
    $query.=" from table1 ;";    
}

echo $query; //check the query