有人可以告诉我如何从两个数据库表中保存字段吗?
这适用于一个表:
$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”,“密钥”和“文本”仅存在于DB1上。
答案 0 :(得分:1)
您遇到的问题在于选择数据库。选择第一个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";
答案 1 :(得分:0)
将您的查询更改为:
$result = mysql_query("SELECT column_name FROM information_schema WHERE table_name IN ('".$table."','".$table2."' WHERE column_name NOT IN ('ID','Key','Text');");