Mysql嵌套查询优化

时间:2011-04-27 19:36:42

标签: mysql optimization query-optimization

我有一个表记录CMS的各种交易。它记录用户名,操作和时间。我已经做了以下查询来告诉我每个用户在过去两天内做了多少交易,但是它速度太慢,此时我发送一堆单独的查询的速度更快。我是否缺少编写嵌套查询的基本规则?

SELECT DISTINCT
    `username`
   , ( SELECT COUNT(*)
       FROM `ActivityLog`
       WHERE `username`=`top`.`username`
         AND `time` > CURRENT_TIMESTAMP - INTERVAL 2 DAY
     ) as `count`
FROM `ActivityLog` as `top`
WHERE 1;

2 个答案:

答案 0 :(得分:2)

您可以使用:

   SELECT username
        , COUNT(*) AS count
   FROM ActivityLog
   WHERE time > CURRENT_TIMESTAMP - INTERVAL 2 DAY
   GROUP BY username

(username, time)上的索引对速度有帮助。


如果您希望用户拥有0次转化(过去2天),请使用此选项:

SELECT DISTINCT
    act.username
  , COALESCE(grp.cnt, 0) AS cnt
FROM ActivityLog act
  LEFT JOIN
    ( SELECT username
           , COUNT(*) AS count
      FROM ActivityLog
      WHERE time > CURRENT_TIMESTAMP - INTERVAL 2 DAY
      GROUP BY username
    ) AS grp
  ON grp.username = act.username 

或者,如果您有users表:

SELECT 
    u.username
  , COALESCE(grp.cnt, 0) AS cnt
FROM users u
  LEFT JOIN
    ( SELECT username
           , COUNT(*) AS count
      FROM ActivityLog
      WHERE time > CURRENT_TIMESTAMP - INTERVAL 2 DAY
      GROUP BY username
    ) AS grp
  ON grp.username = u.username 

与你的相似的另一种方式是:

   SELECT username
        , SUM(IF(time > CURRENT_TIMESTAMP - INTERVAL 2 DAY, 1, 0))
          AS count
   FROM ActivityLog
   GROUP BY username

甚至是这个(因为MySQL的true = 1和false = 0):

   SELECT username
        , SUM(time > CURRENT_TIMESTAMP - INTERVAL 2 DAY)
          AS count
   FROM ActivityLog
   GROUP BY username

答案 1 :(得分:0)

无需嵌套......

SELECT `username`, COUNT(`username`) as `count` FROM `ActivityLog` WHERE `time` > CURRENT_TIMESTAMP - INTERVAL 2 DAY GROUP BY `username`

如果你想让它更快,你也不要忘记在time上添加一个INDEX