获取每个组的行数

时间:2014-02-03 13:49:41

标签: mysql

我正在尝试对两个表运行查询:

locations (user, longitude, latitude, name, description, date)

visits (user, longitude, latitude, visit_time)

获取用户在过去x天内访问过的位置列表,其中包含每个位置的总访问次数。

我尝试加入这些列,并按longitudelatitude对结果进行分组:

$dCntMS = $dCnt * 24 * 60 * 60 * 1000;
$currentTimeMS = round(microtime(true) * 1000);
$x = $currentTimeMS - $dCntMS;

$query = "SELECT `locations`.`latitude`, `locations`.`longitude`, `locations`.`name`, `locations`.`description`, `locations`.`date`" . 
         "FROM `locations`, `visits` " . 
         "WHERE `visits`.`user`='$user' " .
             "AND `visits`.`longitude`=`locations`.`longitude` " .
             "AND `visits`.`latitude`=`locations`.`latitude` " . 
             "AND `visits`.`visit_time` >= '$x'" .
        "GROUP BY `longitude`, `latitude`"; 

返回用户在给定时间内访问过的唯一位置,如下所示:

[0] => (
        [latitude] => 42.8903888
        [longitude] => 21.8133837
        [name] => locationName
        [description] => shortLocationDesc
        [date] => 13913465172
       )
[1] => (...)

但我需要在结果集中再添一个列。 像这样:

    (
        [latitude] => 42.8903888
        [longitude] => 21.8133837
        [name] => locationName
        [description] => shortLocationDesc
        [date] => 13913465172
        [totalVisits] => 5
    )

换句话说,要检索每个组中的行数。

我认为我需要COUNT中的SELECT功能,但由于每个位置都由两个属性(longitudelatitude标识),我不知道会是什么正确的做法。

我感谢任何帮助。

更新

谢谢大家@Iqbal,@ Barmar,@Strawberry的帮助!

3 个答案:

答案 0 :(得分:0)

试试这个:

$query = "SELECT `locations`.`latitude`, `locations`.`longitude`, MAX(`locations`.`name`),  count(*) AS TotalVisits" . 
     "FROM `locations`, `visits` " . 
     "WHERE `visits`.`user`='$user' " .
         "AND `visits`.`longitude`=`locations`.`longitude` " .
         "AND `visits`.`latitude`=`locations`.`latitude` " . 
         "AND `visits`.`visit_time` >= '$x'" .
    "GROUP BY `longitude`, `latitude`"; 

答案 1 :(得分:0)

$query = "SELECT l.latitude, l.longitude, l.name," .
         "       l.description, l.date, COUNT(*) AS totalVisits" . 
         "FROM locations AS l " . 
         "INNER JOIN visits AS v ON v.longitude = l.longitude AND v.latitude = l.latitude " .
         "WHERE v.user='$user' " .
         "AND v.visit_time >= '$x' " .
         "GROUP BY longitude, latitude"; 

COUNT(*)函数计算GROUP BY列指定的每个组中的行数。

答案 2 :(得分:0)

请注意,您也可以通过这种方式编写Barmar的查询。我觉得它看起来更好......

$query = "
SELECT l.latitude
     , l.longitude
     , l.name
     , l.description
     , l.date
     , COUNT(*) totalVisits
  FROM locations l 
  JOIN visits v 
    ON v.longitude = l.longitude 
   AND v.latitude = l.latitude 
 WHERE v.user = '$user' 
   AND v.visit_time >= '$x' 
 GROUP 
    BY longitude, latitude;
";