[英]SQL multiple table query with UNION, how to get table names
I have the following table structure. 我有以下表格结构。 One table EQUITIES and a table for each row in this table.
一个表EQUITIES,此表中的每一行都有一个表。
EQUITIES table:
id instrument
and tables for every instrument with are all similar to this: Tables named like EE5367126893 (various names and the names are stored in equities table). 每个工具的表都与此类似:命名为EE5367126893的表(各种名称和名称存储在权益表中)。
EE5367126893
id chg
EDIT: My code is BAD. 编辑:我的代码很糟糕。 It somehow gets me wrong results and i can't seem to find an error.
它以某种方式使我得到错误的结果,而且我似乎找不到错误。
<?
//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);
?>
It got me results: 它给了我结果:
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
)
Its pretty obvious that I'm not getting the the highest, lowest or values with most vol (as -0.84>-5.03).It looks like random values got locked with this query. 很明显,我没有获得最高,最低或具有最大vol的值(如-0.84> -5.03),似乎随机值已被该查询锁定。 Where's the catch?
哪里有收获? Im pretty sure theres something bad with my sql query...
我很确定我的sql查询有问题...
You can add name to select 您可以添加名称以进行选择
SELECT id, chg, 'table_name or instrument_name' as inst_name from ...
Example: 例:
$sqlx .= "(SELECT id, chg, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
It seems that vol has got VARCHAR type and rows are sorted by chars not by integers. 似乎vol具有VARCHAR类型,并且行按char而不是整数排序。 Could you provide your table scheme?
您能提供您的餐桌方案吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.