简体   繁体   中英

Calculate date difference in MySQL and PHP

Let's say we have a MYSQL database, 'employees.'

The database contains a column, "EXP," which contains a String signifying the persons START DATE... example: "2015-01-11" (formatted: yyyy-mm-dd)

I would like for database queries to return a variable "experience" which is calculated by comparing the current date to the date contained in the EXP column.

This is the most recent attempt; what I'm trying:

SELECT phone, name, (DATEDIFF('CURDATE()','EXP') AS experience, bio, photo,  FROM squad

Can you tell what I am trying to accomplish? If anyone knows the correct code to put here it would be greatly appreciated.

Please note, if I simply replace the code

(DATEDIFF('CURDATE()','EXP') AS experience

with 'EXP' , then there are no errors and everything works as expected.

you have extra brackets AND 'EXP' will use the string literal not the db field

    SELECT phone, name, DATEDIFF(now(), exp) AS experience, bio, photo
FROM squad

working demo: http://sqlfiddle.com/#!9/79e87/2

From what I understood from your question and from the select statement, I think you just have a wrong syntax check the below query

SELECT phone, name, DATEDIFF(now(), exp) AS experience, bio, photo
FROM squad

删除CURDATE()周围的引号,它是函数,因此不需要引号

SELECT phone, name, (DATEDIFF(CURDATE(), EXP) AS experience, bio, photo,  FROM squad

尝试

SELECT phone, name, DATEDIFF(CURDATE(),EXP) AS experience, bio, photo,  FROM squad

Try this query,

    SELECT 
            phone, name, 
            CONCAT( 
                    FLOOR(TIMESTAMPDIFF(MONTH,exp,CURDATE())/12),
                    ' Year(s), ', 
                    (TIMESTAMPDIFF(MONTH,exp,CURDATE())%12),
                    ' Month(s)'
                  ) AS experience,
            bio, photo  
    FROM 
            squad;

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