2011-08-20 58 views
0

我有如下表結構。一個表中的EQUITIES和表格中的每一行。用UNION進行SQL多表查詢,如何獲取表名

EQUITIES table: 
id instrument 

和表與每個儀器都與此類似: 表命名爲喜歡EE5367126893(不同的名稱和名稱都存儲在股市表)。編號: 我的代碼是壞的。它以某種方式讓我錯誤的結果,我似乎無法找到一個錯誤。

<? 
//CREATION OF TOP MOVERS 
include('connect.php'); 
$sql = "SELECT * FROM equities";  

$result = mysql_query($sql) or die(mysql_error()); 

$instruments = array(); 
while ($row = mysql_fetch_array($result)) { 
    array_push($instruments, $row["instrument"]); 
} 
$i=0; 
foreach($instruments as $instrument) { 
    $sqlx .= "(SELECT id, chg, vol, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)"; 
    if ($i<count($instruments)-1){ 
      $sqlx .= " UNION "; 
      $i++; 
    } 
} 
$gsql = $sqlx; 
$lsql = $sqlx; 
$vsql = $sqlx; 

//Gainers 
$gsql .= " ORDER BY chg DESC LIMIT 3"; 
$gresult = mysql_query($gsql) or die(mysql_error()); 
while ($grow = mysql_fetch_array($gresult)) { 
    $g[$grow['name']] = $grow['chg'];; 
} 
print_r($g); 
//losers 
$lsql .= " ORDER BY chg ASC LIMIT 3"; 
$lresult = mysql_query($lsql) or die(mysql_error()); 
while ($lrow = mysql_fetch_array($lresult)) { 
    $l[$lrow['name']] = $lrow['chg'];; 
} 
print_r($l); 
//most volume 
$vsql .= " ORDER BY vol DESC LIMIT 3"; 
$vresult = mysql_query($vsql) or die(mysql_error()); 
while ($vrow = mysql_fetch_array($vresult)) { 
    $v[$vrow['name']] = $vrow['vol'];; 
} 
print_r($v); 
?> 

這讓我的結果:

Array 
(
    [LV0057869] => 0.68 
    [EE310054309] => 0.00 
    [EE3100034553] => -5.03 
) 
Array 
(
    [LV0054359] => -0.84 
    [LT0000543337] => -3.83 
    [LT00453127375] => -4.03 
) 
Array 
(
    [EE310054334653] => 791 
    [EE3100003609] => 58538 
    [LT000543337] => 33240 
) 

它很明顯,我不跟大部分體積得到的最高,最低或值(如-0.84> -5.03)。它看起來像隨機值被這個查詢鎖定。漁獲何處? Im相當肯定那裏有什麼不好與我的SQL查詢...

回答

0

您可以添加名稱來選擇

SELECT id, chg, 'table_name or instrument_name' as inst_name from ... 

例子:

$sqlx .= "(SELECT id, chg, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)"; 

看來,體積得到了VARCHAR類型和行按字符排序,不是整數。 你能否提供你的餐桌方案?

+0

你救了我的一天!謝謝!爲什麼我不能拿出這個。簡單強勁 – Josh

+0

歡迎您! –

+0

看來這是最佳解決方案。 –