mysql按另一列和组结果计算不同的行

时间:2017-01-24 01:33:42

标签: php mysql

我有一张搜索记录表。列是IP,查询,时间戳。我想要的是通过“查询”对数据进行分组,并计算该“查询”的IP地址唯一实例的数量。以下是该表的示例:

TABLE: SEARCHES
IP    |    query    |     timestamp
1.2.3.4    oranges        1485215625
1.2.3.5    bananas        1485215643
1.2.3.4    oranges        1485215655
1.2.3.6    apples         1485215662
1.2.3.7    oranges        1485215711
1.2.3.7    pears          1485215730

我正在使用以下mysql查询:

SELECT query, COUNT(query) as num FROM searches WHERE timestamp > ".$sometimestamp." GROUP BY query

我的目标是检索以下数据:

oranges [2]
bananas [1]
apples  [1]
pears   [1]

我的查询很接近,但会产生:

oranges [3]  <-- IP address 1.2.3.4 searched for this twice, counting 3  total
bananas [1]
apples  [1]
pears   [1]

我需要一种方法,它只能为每个IP地址计算一次唯一的搜索查询(但不能忽略来自同一IP地址的多个唯一查询)。

1 个答案:

答案 0 :(得分:1)

使用count distinct:

SELECT 
    `query`, 
    COUNT(DISTINCT `IP`) as num 
FROM `searches`
WHERE `timestamp` > ".$sometimestamp."
GROUP BY `query`
相关问题