压缩一个Mysql查询

时间:2014-11-03 22:08:49

标签: mysql optimization

我希望将这三个mySql查询压缩成一个查询

$qry = "SELECT DISTINCT authentication_id FROM gps_trak WHERE DATE(location_timestamp) = DATE(NOW())";

我使用上述查询获取身份验证,然后循环搜索结果以获取当前该人的每个纬度和经度,并获取他/她的名字......

$qry ="SELECT latitude, longitude FROM gps_trak WHERE authentication_id = ".$authID." ORDER BY location_timestamp DESC LIMIT 8";

$qry = "SELECT CONCAT('forename ', 'surname') AS name FROM authentication WHERE authentication_id = ".$authID;

你能把它写成单一查询,以便我得到

$resultset=array("id"=>$authID,"name"=>$name,"locs"=>$locArray);

*编辑:* gps_trak表中的单个authkey可以有多个纬度和经度值......

1 个答案:

答案 0 :(得分:0)

我没有安装MySql,但查询的内容如下:

SELECT a.authentication_id, CONCAT(a.forname, a.surname) AS name, g.latitude, g.longitude, g.location_timestamp
FROM authentication a
INNER JOIN gps_trak g on a.authentication_id = g.authentication_id
WHERE DATE(g.location_timestamp) = DATE(NOW()) 
GROUP BY a.authentication_id, a.forname, a.surname, g.latitude, g.longitude, g.location_timestamp

您无法在此解决方案中使用限制,您必须将结果分组到代码中。也许是这样的PHP group by和由authentication_id分组。

修改

更新了SQL。在PHP中做这样的事情(详情请看上面的链接):

<?php
$result = mysql_unbuffered_query($qry);
$set = array();
while ($record = mysql_fetch_object($result)) {
  $set[$record->authentication_id][] = $record;
}
mysql_free_result($result);
foreach ($set as $authentication_id => $records) {
  /* do something with your name and auth key*/
  foreach ($records as $record) {
    /* do something with the long and lat and you can limit it to 8 results sorting with rsort() for descending*/
  }
}
?>