根据自定义计算字段筛选行

时间:2014-02-08 13:31:21

标签: mysql sql

我想过滤使用WHERE条件返回的行。问题是MySQL不允许我在WHERE子句中使用自定义列名。它给出了语法错误。

SELECT jobs.*,

        CASE
            WHEN job_status = 'submitted'           THEN ((2 * 86400) - ($mktime - job_timestamp))/86400
            WHEN job_status = 'agreement_pending'   THEN ((1 * 86400) - ($mktime - job_tstamp_agpending))/86400
            WHEN job_status = 'payment_complete'    THEN ((job_duration * 86400) - ($mktime - job_tstamp_pcomplete))/86400
            ELSE 1000000
        END AS sla

FROM jobs 
WHERE sla < 0

是否仍然可以将行排除WHERE sla < 0条件?

2 个答案:

答案 0 :(得分:1)

MySQL有一个特殊的扩展,您可以使用having子句来执行此操作:

SELECT jobs.*,

        CASE
            WHEN job_status = 'submitted'           THEN ((2 * 86400) - ($mktime - job_timestamp))/86400
            WHEN job_status = 'agreement_pending'   THEN ((1 * 86400) - ($mktime - job_tstamp_agpending))/86400
            WHEN job_status = 'payment_complete'    THEN ((job_duration * 86400) - ($mktime - job_tstamp_pcomplete))/86400
            ELSE 1000000
        END AS sla

FROM jobs 
HAVING sla < 0;

其他数据库不支持此功能。

答案 1 :(得分:1)

所有RDBMS的有效解决方案都使用派生表:

SELECT *
FROM
  (
    SELECT jobs.*,
        CASE
            WHEN job_status = 'submitted'           THEN ((2 * 86400) - ($mktime - job_timestamp))/86400
            WHEN job_status = 'agreement_pending'   THEN ((1 * 86400) - ($mktime - job_tstamp_agpending))/86400
            WHEN job_status = 'payment_complete'    THEN ((job_duration * 86400) - ($mktime - job_tstamp_pcomplete))/86400
            ELSE 1000000
        END AS sla
    FROM jobs 
  ) AS dt
WHERE sla < 0