为foreach循环限制查询并保持排序顺序

时间:2016-01-20 14:02:33

标签: php mysql sql

  $m = format_date(time(), 'custom', 'm');
  $sql ="
  SELECT cwf.sport, 
  SUM(cwf .time) AS total
  FROM `data`  ww
  INNER JOIN table cwf ON cwf.id = ww.id
  where ww.nid = 2897  AND MONTH(FROM_UNIXTIME(ww.submitted)) = {$m}
  GROUP BY sport ORDER BY total DESC LIMIT 5";  

  $results = db_query($sql)->fetchall();
  collect = array();
 $before = array();
  foreach($results as $object) {
     $name = $object->sport;
     $nid = db_query("SELECT nid FROM {node} WHERE  LOWER(title) = :title AND type = 'sport'", array(":title" => trim(strtolower($name))))->fetchField();
     if($nid) {  
       $minutes = $object->total;
       $count =  db_query('SELECT field_' . $m . '_value FROM {field_revision_field_'. $m . '} WHERE  entity_id = :nid', array(":nid" => $nid))->fetchField();
       $real = round($minutes/$count);
       $before[$name] = $minutes; 
       collect[$name] = $real;    
     }
  }
  uasort(collect, 'cmp');

foreach(collect as $k => $v):?>

           <tr">
                <td>&nbsp;</td>
               <td><?php echo $k; ?></td>
                 <td align="right"><?php echo $v; ?></td>
                <td align="right"><?php echo $before[$k]; ?></td>
               <td>&nbsp;</td>
           </tr>

<?php endforeach;
      echo "</table>";
?>

我有这个查询打印三列这样的

SPORT   Average Total Time
sport1  4       700  
sport2  9       600
sport3  3       800  
sport4  2       500  

我想限制2,以便按平均值下降表格,而不是像这样的总时间。现在,当我向查询添加限制5时,它按总计排序。我认为它根本不在SQL中,但可能使用循环和break语句只能将foreach增加++ 2。

    SPORT   Average Total
    sport1  9       600  
    sport2  4       700
    sport3  3       800  
    sport4  2       500   

1 个答案:

答案 0 :(得分:1)

不确定您的数据库模型是什么样的(从您的代码中看起来很奇怪......),但是将它变成单个查询并不容易。更好的性能,然后MySQL可以解决您的订购问题。

未经测试,缺少您的数据库模型/数据,但这样的事情应该有效:

SELECT cwf.sport, ROUND(total / frf.field_' . $m . '_value) AS avg, SUM(cwf .time) AS total
  FROM `data`  ww
  INNER JOIN table cwf ON cwf.id = ww.id
  JOIN {node} n ON LOWER(n.title) = cwf.sport AND n.type='sport'
  JOIN {field_revision_field_'. $m . '} frf ON frf.entity_id = n.nid
  where ww.nid = 2897  AND MONTH(FROM_UNIXTIME(ww.submitted)) = {$m}
  GROUP BY sport ORDER BY avg DESC LIMIT 5