0

有人可以告诉我如何保存两个数据库表中的字段吗?

这适用于一张桌子:

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text');");

$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";`

我需要来自两个不同表的字段。我在同一台机器上有两个数据库。表中的字段名称不同。

不起作用

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
mysql_select_db($db2) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table." , ".$table2."  WHERE Field NOT IN 
('ID','Key','Text');");

$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";

字段“ID”、“Key”和“Text”仅存在于 DB1 上。

4

2 回答 2

1

您遇到的问题在于选择数据库。选择第一个 DB 后,您立即选择第二个 DB,它将覆盖前一个 DB,因此所选 DB 是最后的第二个 DB。
一种解决方案是选择第一个数据库,获取您需要的列名,将它们保存在您$csv_output$csv_output.
Usman提出的解决方案也不错,方法如下

USE information_schema;  -- select the correct DB
SELECT column_name FROM columns WHERE table_name IN ('table1', 'table2');

希望有帮助!

更新

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());

// get the column name from the first DB
mysql_select_db($db1, $link) or die("Can not connect to DB1.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text')");    
$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}

// get the column names from the second DB
mysql_select_db($db2, $link) or die("Can not connect to DB2.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE 1");
$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";
于 2012-08-09T10:37:41.643 回答
0

将您的查询更改为:

$result = mysql_query("SELECT column_name FROM information_schema WHERE table_name IN ('".$table."','".$table2."' WHERE column_name NOT IN ('ID','Key','Text');");
于 2012-08-09T10:01:16.080 回答