简体   繁体   English

Mysql/PHP 合并两张表

[英]Mysql/PHP Merge two tables

How can I merge two tables into one table?如何将两张表合并为一张表?

For example, let say I have table named person with first_name and last_name,gender then I have another table called person_d and this has first_name, last_name, telephone and email.例如,假设我有一个名为 person 的表,其中包含 first_name 和 last_name,gender,然后我有另一个名为 person_d 的表,它有 first_name、last_name、telephone 和 email。

The new table should contain first_name, last_name, telephone and email,gender新表应包含 first_name、last_name、telephone 和 email,gender

but i want to do that in an automatic way without even know what the fields name are just by using a conditions但我想以自动方式做到这一点,甚至不知道字段名称是什么,只是通过使用条件

Is that possible with sql or i have to do it using php? sql 是否可能,或者我必须使用 php 来做到这一点? I thought that I can create php script and get fields name into two arrays then compare for doubles and add them to new array and delete them after that we will have arrays with no doubles this is my code我认为我可以创建 php 脚本并将字段名称放入两个 arrays 然后比较双精度并将它们添加到新数组并删除它们之后我们将有 arrays 这是我的代码

    <?php


$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";



//mysql and db connection

$db = new mysqli($servername, $username, $password, $dbname);

if ($db->connect_error) {  //error check
    die("Connection failed: " . $con->connect_error);
} else {

}


$query1 = $db->query("SELECT * FROM     tablename1");
$query2 = $db->query("SELECT * FROM     tablename2");
$table1 = array();
$table2 = array();
$newtable = array();

while ($property = mysqli_fetch_field($query)) { //fetch table field name

    array_push($table1,$property->name);

}

while ($property = mysqli_fetch_field($query)) { //fetch table field name

    array_push($table2,$property->name);

}


foreach($table1 as $field1) { 
    foreach($table2 as $field2) { 
        if ($field1==$field2)
        {
            array_push($newtable,$field1);
            unset($table1[$field1]);
            unset($table1[$field2]);

        }

    }

}

and after that i create new table with fields from arrays side by side之后,我并排创建包含 arrays 字段的新表

Is this the best way or there is another way to do that?这是最好的方法还是有另一种方法可以做到这一点?

no need for PHP in here.这里不需要 PHP。 This can be done in SQL only.这只能在 SQL 中完成。

INSERT INTO new_table (first_name, last_name, telephone, email)
SELECT first_name, lastname, telephone, email
FROM person_d;

And afterwards之后

INSERT INTO new_table (first_name, last_name)
SELECT first_name, lastname
FROM person
ON DUPLICATE KEY IGNORE;

This requires you make the combination of first and last name UNIQUE这要求您将名字和姓氏的组合设为 UNIQUE

You could of course change the names of the columns.您当然可以更改列的名称。 And I suppose this is an exercise to do only once我想这是一个只能做一次的练习

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

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