寻找独特访客的更好解决方案

时间:2013-03-18 06:49:40

标签: mysql sql subquery

我正在使用以下查询来查找每个表格中每天的唯一身份访问者数量。但这会影响性能。任何人都可以建议更好的解决方案。我目前的疑问是:

SELECT t.date,COUNT(DISTINCT t.uID) as unique_clicks FROM table_name t
WHERE
    NOT EXISTS(
        SELECT 1
        FROM table_name t2
        WHERE
            t2.uID = t.uID
            AND t2.date < (t.date)
    )
GROUP BY t.date

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

SELECT
  t.date, COUNT(DISTINCT t.uID) as unique_clicks
FROM
  table_name t LEFT JOIN table_name t1
  ON t.uID=t2.uID AND t2.date < t.date
WHERE
  t2.uID is NULL
GROUP BY t.date

我认为在这种特殊情况下,连接应该比EXISTS子句更快。或者,如果我正确理解逻辑,那么:

SELECT min_date, COUNT(*) as unique_clicks
FROM (
  SELECT
    t.uID, min(t.date) min_date
  FROM
    table_name t
  GROUP BY
    t.uID
  ) s
GROUP BY min_date

请参阅小提琴here