简体   繁体   中英

Insert into another table where the columns exist in table 2

I want to insert the values of table 1 into table 2, where the columns in table 2 exist in table 1. For more reference see this tables:

Table 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  |
+----------+----------+----------+

Table 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  |          |          |
+----------+----------+----------+----------+----------+

If the columns in table 2 doesn't exist in table 1 it inserts null value.

Thanks in advance!

You can set default value for col 4 & col 5 to NULL and then run this query :

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

It should work but you have to explicitly specify the columns in common between the two tables.

Try this:

<?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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