Mysql复杂查询,按限制分组

时间:2014-06-30 12:43:14

标签: mysql sql select subquery limit

我是下表

store_visits: (store_id, city_id, date, visits, ...)

我想选择按访问次数排序的最多5家商店。

SELECT X.* 
  FROM (
    SELECT 
      store_id, SUM(visits) as sum_visits FROM store_visits
    WHERE 
      (date <= '2014-06-28' AND  date >= '2014-06-27') 
    AND 
      store_visits.city_id = 2 
    GROUP BY 
      store_id 
    ORDER BY 
      sum_visits desc
  ) X 
LIMIT 5

我想知道是否有办法增强查询以释放临时表和文件。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT store_id, SUM(visits) AS sum_visits 
FROM store_visits sv
WHERE sv.date <= '2014-06-28' AND sv.date >= '2014-06-27' AND sv.city_id = 2 
GROUP BY store_id 
ORDER BY sum_visits DESC LIMIT 5