使用日期条件将多个MySql查询组合到单个查询中

时间:2012-06-08 11:56:27

标签: mysql sql

我有一个名为users的表。

id   name date       cdate           c  a   b
1     rz  42121221  42121221         0  1   0
2     an  12122111  42121221         0  0   1
3     cb  22121221  42121221         1  1   1   
4     ss  3321221   42121221         1  0   0

我必须选择两个日期之间的值,然后我必须使用此语句查找计数。

 SELECT COALESCE(SUM(IF(c=1 AND a=0 AND b=1  ,  1, 0)),0) AS ACTIVE
   WHERE DATE BETWEEN 'DATE 1' AND 'DATE 2',
 COALESCE(SUM(IF(c=0 AND a=0 AND b=1  ,  1, 0)),0) AS INC
   WHERE cdate BETWEEN 'DATE 1' AND 'DATE 2'
 FROM users where dealer id='2'

此查询无效。

2 个答案:

答案 0 :(得分:0)

这是您的查询,格式正确。每个SELECT语句只能有一个WHERE子句,FROM子句位于SELECT子句之后和WHERE子句之前。

 SELECT SUM(IF(c=1 AND a=0 AND b=1 AND DATE BETWEEN 'DATE 1' AND 'DATE 2', 1, 0)) AS ACTIVE,
   SUM(IF(c=0 AND a=0 AND b=1 AND cdate BETWEEN 'DATE 1' AND 'DATE 2', 1, 0)) AS INC
 FROM users
 WHERE DATE BETWEEN 'DATE 1' AND 'DATE 2'
   OR cdate BETWEEN 'DATE 1' AND 'DATE 2'

我将日期比较复制到IF语句中。

另外,我删除了COALESCE子句,因为在这种情况下它是多余的。 SUM总是返回一个值。

我在SELECT子句之后将列放在一起,用逗号分隔。

您可能希望立即删除WHERE子句,具体取决于您要执行的操作。

我也怀疑cdate BETWEEN 'DATE 1' AND 'DATE 2'。如果cdate是DATETIME列,则需要在常量中放入格式正确的日期。如果DATE 1和DATE 2是列名,那么你需要返回刻度,而不是单引号,如下所示:

cdate BETWEEN `DATE 1` AND `DATE 2`

您应该考虑阅读SELECT syntax上的文档。

答案 1 :(得分:0)

我会做这样的事情来在一个查询中实现你的需要:

试一试:

SELECT COALESCE(SUM(IF(u1.c=1 AND u1.a=0 AND u1.b=1, 1, 0)),0) AS ACTIVE,
COALESCE(SUM(IF(u2.c=0 AND u2.a=0 AND u2.b=1, 1, 0)),0) AS INC
from user u1
left outer join user u2 on u1.row_id = u2.row_id
where u1.DATE BETWEEN 'DATE 1' AND 'DATE 2' and
u2.cdate BETWEEN 'DATE 1' AND 'DATE 2'