Monday, 2 September 2013

Pass MySql time unit parameter as an expression

Pass MySql time unit parameter as an expression

I have the following table tequipment:
+----------+---------------------------------+------------------------------------------------+--------------------+
| id | expiration_periodicity_value |
expiration_periodicity_type | setting_up_date |
+----------+---------------------------------+------------------------------------------------+--------------------+
| 1 | 5 | MONTH
|2013-09-02 13:14:09 |
+----------+---------------------------------+------------------------------------------------+--------------------+
| 2 | 1 | YEAR
|2013-09-02 13:14:09 |
+----------+---------------------------------+------------------------------------------------+--------------------+
I want to generate a view which says if the equipment is expired
(perished). So, having the NOW() function which in MySql returns the
current datetime, I want to substract to it the expiration periodicity
value and the expiration periodicity type in order to get if the equipment
is perished comparing it with the setting up date. I wrote that query:
SELECT (DATE_SUB(NOW(), INTERVAL equipment.expiration_periodicity_value
MONTH)
> equipment.setting_up_date) as expired
FROM tequipment equipment;
The query itself works like that, but I want to establish equipment's
expiration_periodicity_type in order than 'MONTH' directly, because it can
be a variable field. However, according to MySql DATE_SUB documentation,
the function is defined like that:
DATE_SUB(date,INTERVAL expr unit)
So first parameter field after INTERVAL is supposed to be an expression
(it accepts the value unit because of that), but unit itself seems to be a
fixed one. Do I have any chance to set it in one go or do I need any
conditional evaluation which will perform one substraction type or other
depending on the field?

No comments:

Post a Comment