简体   繁体   中英

Filter rows based on a custom calculated field

I would like to filter the rows returned using a WHERE condition. The problem is that MySQL is not allowing me to use a custom column name in the WHERE clause. It gives a syntax error.

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

Is it possible to still filter rows out WHERE sla < 0 condition?

MySQL has a special extension where you can do this using the having clause:

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;

This is not supported in other databases.

A valid solution for all RDBMSes uses a Derived Table:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM