有人可以解释以下查询之间的差异:
查询1(返回87结果):
SELECT userId, COUNT(userId) as usercount
FROM `cpnc_PaymentOrder`
WHERE created >= UNIX_TIMESTAMP('2011-03-01')
GROUP BY userId
HAVING usercount > 1
查询2(返回177结果):
SELECT userId, COUNT(userId) as usercount
FROM `cpnc_PaymentOrder`
WHERE created >= UNIX_TIMESTAMP('2011-02-01')
GROUP BY userId
HAVING usercount > 1
查询3(返回55结果):
SELECT userId, COUNT(userId) as usercount
FROM `cpnc_PaymentOrder`
WHERE created >= UNIX_TIMESTAMP('2011-02-01')
AND created < UNIX_TIMESTAMP('2011-03-01')
GROUP BY userId
HAVING usercount > 1
现在我认为来自查询2的结果数减去查询1的结果数等于查询3的结果数。但事实并非如此。有人可以解释一下原因吗?
谢谢,乔纳
编辑:
为了澄清,我想写的查询是:
SELECT userId
FROM `cpnc_PaymentOrder`
WHERE created >= UNIX_TIMESTAMP('2011-02-01')
AND created < UNIX_TIMESTAMP('2011-03-01')
AND userId "appears in at least one other record from before '2011-03-01'"
答案 0 :(得分:5)
因为您要比较组数。
让我们看一个小例子:
user_id | created
1 | 2011-02-02
1 | 2011-02-02
1 | 2011-02-02
2 | 2011-02-02
2 | 2011-02-02
1 | 2011-03-02
1 | 2011-03-02
2 | 2011-03-02
2 | 2011-03-02
此数据集的第一个查询将返回2行,第二个也将返回2行,第3个也将返回2行。
只需删除您的GROUP BY
并查看差异(当然,数学不匹配GROUP BY
)
答案 1 :(得分:0)
查询1包含:WHERE created
&gt; = UNIX_TIMESTAMP('2011-03-01')
即。日期大于......
查询3包含:WHERE created
&lt; UNIX_TIMESTAMP('2011-03-01')
即。日期小于......
因此,查询3不是查询1和2的交集。
答案 2 :(得分:0)
user_id | created
1 | 2011-02-02
1 | 2011-03-02
1 | 2011-03-02
Query1将是1个结果,Query2也是1个结果,但是查询3的结果为零,因为您错过了那个时间内只出现过一次的人。