Imagine the following table (it has other rows but the ones shown below being used in the query),
+-------------------+-----------------+---------------------+
| INTERVAL_QUANTITY | INTERVAL_UOM_ID | LAST_UPDATED_STAMP |
+-------------------+-----------------+---------------------+
| 10 | TF_wk | 2017-10-31 17:21:40 |
| 20 | TF_mon | 2017-10-30 17:21:40 |
| 30 | TF_day | 2017-10-29 17:21:40 |
+-------------------+-----------------+---------------------+
Key
Now, I have the following query,
SELECT
*
FROM
product_maint
WHERE
( INTERVAL_UOM_ID = 'TF_day' OR INTERVAL_UOM_ID = 'TF_wk' OR INTERVAL_UOM_ID = 'TF_mon' )
AND DATEDIFF( DATE( DATE_ADD( LAST_UPDATED_STAMP, INTERVAL INTERVAL_QUANTITY DAY ) ), DATE( NOW( ) ) ) <= 0;
The issue is, when it selects a row which has a INTERVAL_UOM_ID
of TF_wk
and INTERVAL_QUANTITY
of 10
it actually needs to add on 70
days not 10
days, likewise when the INTERVAL_UOM_ID
is TF_mon
and the INTERVAL_QUANTITY
is 20
it needs to add on 560
days (assuming all my math is correct).
How would I go about implementing this logic?
You need to check each interval separately. I think you want:
WHERE ( INTERVAL_UOM_ID = 'TF_day' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY DAY
) OR
( INTERVAL_UOM_ID = 'TF_wk' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY WEEK
) OR
( INTERVAL_UOM_ID = 'TF_mon' AND
LAST_UPDATED_STAMP > CURDATE() - INTERVAL INTERVAL_QUANTITY MONTH
)
Note that I changed the NOW()
to CURDATE()
. I don't think the time component is important for what you want to do. Also note that I changed the logic to work only with date arithmetic.