尝试将多个数据库表组合到一个表中

时间:2013-06-03 00:03:05

标签: mysql database union

由于某些原因,使用以下代码组合多个表不起作用。我想删除重复项,因此我假设 UNION 使用正确,不使用UNION ALL。

如何将database1,database2和database3中的所有三个数据库表组合到database4中的单个表中?

所有数据库表都具有相同的结构。

<?php
 // Variable definitions omitted

       // Connect to all 4 Databases
            $connection1 = mysql_connect($host1, $username1, $password1) or die ('Cannot connect to the database because: ' . mysql_error());
            $connection2 = mysql_connect($host2, $username2, $password2) or die ('Cannot connect to the database because: ' . mysql_error());
            $connection3 = mysql_connect($host3, $username3, $password3) or die ('Cannot connect to the database because: ' . mysql_error());
            $connection4 = mysql_connect($host4, $username4, $password4) or die ('Cannot connect to the database because: ' . mysql_error());

       // Merge all 4 Databases into the Search Database 4
            mysql_select_db ($database4);
            mysql_query("
             SELECT * FROM $database4.$TableName4
             UNION
             SELECT * FROM $database1.$TableName1
             UNION
             SELECT * FROM $database2.$TableName2
             UNION
             SELECT * FROM $database3.$TableName3
             ");

       // Close databases connections
            mysql_close($connection1);
            mysql_close($connection2);
            mysql_close($connection3);
            mysql_close($connection4);
?>

0 个答案:

没有答案