【问题标题】:Insert into another table where the columns exist in table 2插入到表 2 中存在列的另一个表中
【发布时间】:2013-06-04 09:04:57
【问题描述】:

我想将表 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  |          |          |
+----------+----------+----------+----------+----------+

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

提前致谢!

【问题讨论】:

  • 动态插入
  • 表 1 中的哪些列将进入表 2 中的哪些列?
  • col_1、col_2、col_3、col_4 和 col_5 是列的名称。所以 table_1.col_1 去 table_2.col_1,table_1.col_2 去 table_2.col_2 在 col_3 中相同
  • 显示你的 php 插入代码。
  • 我没有,我只是想问一下这是否可能以一种简单的方式

标签: php sql-server


【解决方案1】:

试试这个:

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

【讨论】:

  • 非常感谢先生,此代码对 Mr.Bere 有效
  • 我刚做了。抱歉,我是新手。
【解决方案2】:

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

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
相关资源
最近更新 更多