是否可以在SQL中使用if语句?

时间:2014-09-17 18:06:10

标签: php mysql sql

所以基本上我有一个数据库,可以保存电子邮件活动的排队电子邮件。

电子邮件可能有许多不同的状态,如果电子邮件失败,则会重新尝试。

该表格如

id       email              status      attempts

0       test@test.com       failed         4

0       test@test.com       success        2

0       test@test.com       success        1

0       test@test.com       failed         2

0       test@test.com       new            0

我想了解到目前为止发送过的所有电子邮件或尝试过多的电子邮件。

换句话说,计算所有状态!=' new'的电子邮件,但如果状态='则失败'只计算4或更高的尝试次数。

这可能是SQL查询,还是我必须在PHP中执行此操作?

提前致谢!

5 个答案:

答案 0 :(得分:3)

你可以写

WHERE status = 'success'
   OR status = 'failed' AND attempts >= 4

答案 1 :(得分:1)

是的,这是可能的。

您可以添加where条件,并汇总所需的所有结果:

SELECT 
  SUM( IF( STATUS = 'failed' AND attempts >= 4, 1, 0 ) ) AS total_failed 
, SUM( 1 ) AS total_olds
FROM my_table
WHERE STATUS != 'new'

如果匹配IF条件,则总和仅添加值1。在MySQL中,如果IF子句匹配,则应用第一部分,否则应用第二部分(http://dev.mysql.com/doc/refman/5.0/en/if.html)这里,我们说"嘿,如果条件匹配,则总和1行,否则,什么都不做&#34 ;,这样就可以将所有结果集中在一行XD。

因为我们只选择不是新的'行,只添加1(SUM(1))我们将获得匹配的所有行的值。

答案 2 :(得分:0)

   add a where clause to your select as:
    where status ="success" or status = "failed" and attempts >= 4 

如果您不想选择此条件,则无需添加status !='new'

答案 3 :(得分:0)

您可以使用带表达式的sum来编写查询,在Mysql中它被评估为boolean,因此,首先使用表达式求和将为您提供状态不等于失败的电子邮件的计数,并且使用表达式求和将给出计数状态失败并且尝试次数超过3,然后将两个表达式的结果相加,将为您提供所需的计数

select email
sum(status <> 'failed') + sum(status = 'failed' and attempts > 3)  as your_count
from table   
where status <> 'new'      

答案 4 :(得分:0)

请尝试以下查询:

SELECT 
COUNT(email)


FROM 'your table'

WHERE 
STATUS = 'success'
OR 
(STATUS = 'failed' AND attempts >=4)