简体   繁体   中英

How to Trigger total number of days in mySQL

"I need to create a field that will show the number of days between a date and the present.

TABLE:  reg_add

+------------+---------+
| Name       | Type    |
+------------+---------+ 
| hm_date    | date    |
+------------+---------+ 
| total_days | date    |
+------------+---------+ 

My client will type in the following date for example in "hm_date": May 1, 2012.

I need "total_days" to show the total days between May 1, 2012 at the current date.

I want to achieve this on server-side, which is somewhat new to me.

I need to create a TRIGGER to always have "total_days" updated

I started with this and I'm having trouble making a trigger and getting it correct:

SELECT DATEDIFF(curdate(),hm_date) as total_days FROM reg_add

Any help would be appreciated.

Erik

您可以使用TIMESTAMPDIFF函数非常轻松地实时计算它-

SELECT TIMESTAMPDIFF(DAY, hm_date, NOW()) FROM reg_add;

I took a look into the MySQL Trigger Docs and from the looks of it, you can only create trigger for event types Insert, Update, and Delete. So your Trigger won't actually update your total_days field (which should be int) as you want it. [It sounds like you want it to update your field on a time basis (aka every x hours update)].

Here is the docs: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

I would suggest writing a cron job in php that runs once (or multiple times) per day that will update the field for you.

In your cron you should just have to run one sql statement: (This should go through the whole table and update the total_days field for each row)

UPDATE reg_add SET total_days = DATEDIFF(curdate(),hm_date)

Erik, I am using tsql, and not as familiar with mySQL, but in tsql the DATEDIFF function requires 3 parameters. The sytax is

DATEDIFF(date part, date1, date2).

I would try DATEDIFF(d,GETDATE(),hm_date) AS total_days FROM reg_add

Instead of triggers, you could use a View:

CREATE VIEW reg_add_with_total_days_VIEW
  AS
SELECT hm_date
     , DATEDIFF( CURDATE(), hm_date ) AS total_days
FROM reg_add ;

Then you can use the view, every time you need the total days - which will be calculated on the fly:

SELECT hm_date, total_days
FROM reg_add_with_total_days_VIEW 

You can see it working in SQL-Fiddle

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