Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql date_sub using a field as interval

Tags:

sql

mysql

I need help with mysql and date_sub(). I have a table call Activity

Activity(id,deadline,alert)
Activity(1,'2011-04-18','1 DAY');
Activity(2,'2011-04-13','1 MONTH');

Every row in A have an 'alert', this field indicate how time before the deadline an activity have to reported.

For example

On 2011-04-17 I have to report the activity with 'id' 1
On 2011-03-14 I have to report the activity with 'id' 2

I trying to use date_sub() functions, but I can't use a field as params of this function. Any idea how to fix this?

SELECT * 
  FROM `activities` 
 WHERE date_sub(`deadline`, INTERVAL alert) >= CURDATE();
like image 737
ssalvatori Avatar asked Oct 11 '22 05:10

ssalvatori


1 Answers

Split the alert into 2 fields

Alert_count: integer
Alert_period: enum('hour','day','month','week')

And change the query like so:

SELECT * 
  FROM `activities` 
 WHERE CASE alert_period 
   WHEN 'hour' THEN date_sub(`deadline`, INTERVAL alert_count HOUR) >= CURDATE();
   WHEN 'day' THEN date_sub(`deadline`, INTERVAL alert_count DAY) >= CURDATE();
   ...
 END CASE
like image 152
Johan Avatar answered Nov 03 '22 00:11

Johan