获取按最小值排序的php输出

时间:2015-09-04 07:43:07

标签: php sql database

我的html中有这段代码



<h3>Top Pilots</h3>
<div class="row-fluid">
	<div class="span3">
		<table width="100%">
			<thead><tr><td align="center" colspan="3">Best Landings This Month</td></tr></thead>
			<?php 
			$dbm="SELECT DISTINCT pilotid FROM phpvms_pireps WHERE date_format(submitdate, '%Y-%m') = date_format(now(), '%Y-%m') ORDER BY landingrate DESC";
			$bstm = DB::get_results($dbm);
			$num = count($bstm);
			foreach ($bstm as $btm)
				{
					$d1m=$btm->pilotid;
					$blm1="SELECT * FROM phpvms_pilots WHERE pilotid = '$d1m' ";
					$blm2="SELECT * FROM phpvms_pireps WHERE pilotid = '$d1m' AND date_format(submitdate, '%Y-%m') = date_format(now(), '%Y-%m') ORDER BY landingrate DESC";
					$pblm1 = DB::get_row($blm1);
					$pblm2 = DB::get_row($blm2);
					if($pblm2->landingrate == 0){continue;}
					
			?>
					<tr><td></td><td><?php echo $pblm1->firstname.' '.$pblm1->lastname ;?></td><td align="center"><font color="#009900"><?php echo sort($pblm2->landingrate) ;?> ft/min</font></td></tr>
			<?php 
				} 
			?>
			
		</table>
	</div>
</div>	
&#13;
&#13;
&#13;

我得到的结果就像这样:

enter image description here

这是我的2个表格的结构。第一个是PIREPS,第二个是PILOTS

enter image description here

enter image description here

但是我需要按照从最小到最大的数字排序它们。我感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:0)

替换第一个查询:

$dbm="SELECT * FROM 
    (SELECT 
         pilotid, min(landingrate) as landingrate 
         FROM phpvms_pireps 
         WHERE date_format(submitdate, '%Y-%m') = date_format(now(), '%Y-%m') and landingrate <> 0 
         GROUP BY pilotid) t1 
    ORDER BY landingrate DESC";

如果您有负值,请将min()替换为max()。 在foreach中删除$ blm2查询并显示$ btm-&gt; landingrate

您还可以在第一个查询中使用适当的JOIN替换$ blm1

$dbm="SELECT t1.pilotid,t1.landingrate,t2.firstname,t2.lastname FROM 
    (SELECT 
         pilotid, min(landingrate) as landingrate 
         FROM phpvms_pireps 
         WHERE date_format(submitdate, '%Y-%m') = date_format(now(), '%Y-%m') and landingrate <> 0 
         GROUP BY pilotid) t1
    LEFT JOIN phpvms_pilots t2 ON t1.pilotid = t2.pilotid 
    ORDER BY landingrate DESC";

它还提供更好的性能 - 只有1个查询。

答案 1 :(得分:0)

您可以使用一个sql并使用JOIN。只需使用$ pblm1;

$blm1="SELECT * FROM phpvms_pilots,phpvms_pireps 
WHERE pilotid = '$d1m' 
AND date_format(submitdate, '%Y-%m') = date_format(now(), '%Y-%m') 
AND phpvms_pilots.pilotid = phpvms_pireps.pilotid  
ORDER BY landingrate DESC";