如何从MySQL表中检索10个最新的DISTINCT IP?

时间:2009-06-08 09:09:04

标签: sql mysql group-by sql-order-by

我有一个包含pagehit(规范化)数据的表格,我需要抓住10个最新的独特ips。

我试着这样做:

SELECT * FROM spy_hits ORDER BY date desc GROUP BY ip LIMIT 10;

哪个应该给我这个结果:

+-----+------------+-----+---------+----+------+------+---------+-------+-------+
| id  | date       | ip  | browser | os | page | host | referer | query | agent |
+-----+------------+-----+---------+----+------+------+---------+-------+-------+
| 354 | 1244442065 |   2 |       3 |  2 |   16 |    1 |      47 |    12 |     2 |
| 311 | 1244442000 |   1 |       2 |  1 |   16 |    1 |      36 |    12 |     1 |
+-----+------------+-----+---------+----+------+------+---------+-------+-------+
2 rows in set (0.00 sec)

这是该网站的最新独立访问者。

但是我得到语法错误而不是结果。

所以我必须这样做:

SELECT * FROM spy_hits GROUP BY ip ORDER BY date desc LIMIT 10;

我认为可以。但它给出了这个结果:

+-----+------------+-----+---------+----+------+------+---------+-------+-------+
| id  | date       | ip  | browser | os | page | host | referer | query | agent |
+-----+------------+-----+---------+----+------+------+---------+-------+-------+
| 280 | 1242130841 |   2 |       3 |  2 |   16 |    1 |      47 |    12 |     2 |
| 268 | 1242130818 |   1 |       2 |  1 |   16 |    1 |      36 |    12 |     1 |
+-----+------------+-----+---------+----+------+------+---------+-------+-------+
2 rows in set (0.00 sec)

但是,它在分组之后按日期设置顺序,因此它抓取表中第一个也是最旧的唯一ips。

所以表格如下:

 id --- date
 268    1242130818    (Old)
  |      |
  V      V
 354    1244442065    (New)

但是我希望它在我做小组之前就这样:

 id --- date
 354    1244442065    (New)
  ^       ^
  |       |
 268    1242130818    (Old)

我正在使用PHP,所以如果有人知道如何使用PHP解决方案获得结果。

提前干杯:)

1 个答案:

答案 0 :(得分:3)

如果您DISTINCT IP的人很少:

SELECT  ip, MAX(date) AS maxdate
FROM    (
        SELECT  ip, MAX(date) AS maxdate
        FROM    spy_hits
        GROUP BY
                ip
        )
ORDER BY
        maxdate DESC
LIMIT 10

如果你有很多DISTINCT IP

SELECT  *
FROM    spy_hits so
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    spy_hits si
        WHERE   si.ip = so.ip
                AND si.date > so.date
        )
ORDER BY
        date DESC
LIMIT 10

在此表上创建两个索引:

CREATE INDEX ix_spyhits_date ON spy_hits (date)
CREATE INDEX ix_spyhits_ip_date ON spy_hits (ip, date)

将大大改善这些查询。

有关效果详情,请参阅我的博客中的此条目: