[英]PHP mySQL JOIN with matching column names
注意到一個相當大的問題。 當我加入兩個表時,兩個表中都有一個稱為ID的列,這會導致稍后在PHP equasion中使用錯誤的表ID。
簡單的解決方案是更改列名,但是數據庫中還有其他標准,包括每個表中稱為name的列和其中許多標題的列。
有沒有解決的辦法,還是應該重命名整個數據庫以確保沒有重復的列。
參考代碼
$criteria = "SELECT *
FROM voting_intention,electors
WHERE voting_intention.elector = electors.ID
AND electors.postal_vote = 1
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
AND electors.telephone > 0"
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria"); while($row = mysql_fetch_array($the_elector)) {
return $row['ID']; }
mysql_fetch_row
將以數值數組形式獲取數據
我編寫了此功能來協助完成此任務。 基本上,它會將表名添加到關聯數組的字段名之前。
while($row = mysql_fetch_array($the_elector))
{
return $row['ID'];
}
會成為
while($row = mysql_fetch_table_assoc($the_elector))
{
return $row['voting_intention.ID'];
}
功能:
function mysql_fetch_table_assoc($resource)
{
// function to get all data from a query, without over-writing the same field
// by using the table name and the field name as the index
// get data first
$data=mysql_fetch_row($resource);
if(!$data) return $data; // end of data
// get field info
$fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
// if no field info then just use index number by default
$fields[$index]=$index;
}
else
{
$fields[$index]='';
// deal with field aliases - ie no table name ( SELECT T_1.a AS temp, 3 AS bob )
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
// deal with raw data - ie no field name ( SELECT 1, MAX(index) )
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>
盡管“ Gunnx”解決方案是完全可以接受的,但由於您似乎僅使用結果的ID列,因此我想提出一個替代方案。
SELECT
electors.ID
FROM
voting_intention,electors
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.