mySql返回不正确的结果

时间:2011-05-25 13:40:19

标签: php mysql

我有一个查询

SELECT date, SUM(cimpression) AS cimp, SUM(cclick) AS cclick 
FROM stdaily 
WHERE date BETWEEN :start AND :end 
AND (id = 21 AND id = 32 AND id = 12 AND id = 33)
GROUP BY date
ORDER BY date ASC;

此查询只需返回id等于21,32,12和33的结果,但返回的结果不包含那些特定的ID,不确定究竟是什么错误?有什么建议吗?

5 个答案:

答案 0 :(得分:3)

我认为您正在寻找的是:

SELECT date,SUM(cimpression) AS cimp, SUM(cclick) AS cclick
FROM stdaily
WHERE date BETWEEN :start AND :end 
AND id in (21, 32, 12, 33) 
GROUP BY date 
ORDER BY date ASC;

这将返回结果,其中包含in括号中包含的任何ID。

答案 1 :(得分:1)

您的查询不正确,因为ID不能与所有这些值同时出现:

id = 21 AND id = 32 AND id = 12 AND id = 33 

之前的条件失败,结果为NULL。

试试这个:

id = 21 OR id = 32 OR id = 12 OR id = 33 

答案 2 :(得分:1)

id = 21 AND id = 32 AND id = 12 AND id = 33 

应该是

id = 21 OR id = 32 OR id = 12 OR id = 33 

答案 3 :(得分:1)

你没有指明他应该检查那些id的位置,你传递id的方式也是错误的

WHERE date BETWEEN :start AND :end AND (id = 21 AND id = 32 AND id = 12 AND id = 33 )

应该是这样的:

SELECT date,SUM(cimpression) AS cimp,SUM(cclick) AS cclick 
FROM stdaily 
WHERE date BETWEEN :start AND :end AND id IN (21, 32, 12, 33 ) 
GROUP BY date 
ORDER BY date ASC

答案 4 :(得分:1)

我不知道您的数据是如何构建的,但我很惊讶这会返回任何结果。如何将id分别为21和32?例如,如果我使用

SELECT * FROM users WHERE 1=1 AND (id = 10 AND id = 11);

即使有ids 10和11的用户,我也不会得到结果。

你应该使用OR或更好的IN(21,32,12,33)