2014-01-13 106 views
3

我想查詢一個巨大的數據庫(大約2000萬條記錄)來獲取一些數據。這是我現在正在處理的查詢。MySQL - 獲取兩個日期之間的年齡和天數

SELECT a.user_id, b.last_name, b.first_name, c.birth_date FROM users a 
INNER JOIN users_signup b ON a.user_id a = b.user_id 
INNER JOIN users_personal c ON a.user_id a = c.user_id 
INNER JOIN 
(
SELECT distinct d.a.user_id FROM users_signup d 
WHERE d.join_date >= '2013-01-01' and d.join_date < '2014-01-01' 
) 
AS t ON a.user_id = t.user_id 

我有一些問題,試圖從數據庫中檢索額外的數據。我想在結果表中添加2個附加字段:

  1. 我能夠得到出生日期,但我想要在結果表中獲取成員的年齡。數據在users_personal表中存儲爲'yyyy-mm-dd'。
  2. 我想從使用join_date & left_date(格式:yyyy-mm-dd)的數據,從一個成員加入到左側(如果有)從名爲user_signup的表中離開的天數總和。

回答

1

試試這個:

SELECT a.user_id, b.last_name, b.first_name, c.birth_date, 
     FLOOR(DATEDIFF(CURRENT_DATE(), c.birth_date)/365) age, 
     DATEDIFF(b.left_date, b.join_date) workDays 
FROM users a 
INNER JOIN users_signup b ON a.user_id a = b.user_id 
INNER JOIN users_personal c ON a.user_id a = c.user_id 
WHERE b.join_date >= '2013-01-01' AND b.join_date < '2014-01-01' 
GROUP BY a.user_id 
1

可以使用DATEDIFF函數找到像

select datediff(date1,date2) from table 


select datediff(curdate(),date2) from table 
0

獲取多年來當前兩歲日之間的天數:

SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 AS age FROM table_name; 

工作原理:

  1. datediff(date1,date2)給出了兩個日期之間的差異,以天爲單位。請注意,這裏'生日'的日期格式是日期:YYYY-MM-DD。
  2. from_days將日期轉換爲日期格式
  3. date_format函數僅用'%Y'提取四位數年份。不要使用'%y',因爲你只能得到兩位數的年份,而有些人的年齡則是99歲。
  4. 將字符串與1相乘。這是一個'黑客'。 MySQL會將一個像'YYYY'這樣的字符串轉換成一個整數。

獲得在一個月的當前年齡(unlikley,但有人可能會需要這個)

SELECT (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%Y') * 1 * 12) 
+ (DATE_FORMAT(FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)), '%m') * 1) AS age_in_months 
FROM table_name; 

這是如何工作:

  1. 晴同齡以上年。
  2. 這些年份受到12倍。一個(地球)年有12個月。
  3. 在下一步中,提取的月份與年份的提取方式相同,但標記'%Y'必須更改爲'%m'。
  4. 最後將兩個值相加。

獲得在天目前的年齡是如此簡單:

SELECT DATEDIFF(DATE(NOW()), birthday) AS age_in_days FROM table_name; 

替代代碼:

SELECT 
    DATE_FORMAT(age_date, '%Y') * 1 AS age_in_years, 
    (DATE_FORMAT(age_date, '%Y') * 1 * 12) + (DATE_FORMAT(age_date, '%m') * 1) AS age_in_months, 
    age_in_days 
FROM 
    (SELECT 
     FROM_DAYS(DATEDIFF(DATE(NOW()), birthday)) AS age_date, 
     DATEDIFF(DATE(NOW()), birthday) AS age_in_days 
    FROM table_name) AS age_date; 
3

或者你可以做這個...

SELECT 
    TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age_in_years, 
    TIMESTAMPDIFF(MONTH, birthday, CURDATE()) AS age_in_month, 
    TIMESTAMPDIFF(DAY, birthday, CURDATE()) AS age_in_days, 
    TIMESTAMPDIFF(MINUTE, birthday, NOW()) AS age_in_minutes, 
    TIMESTAMPDIFF(SECOND, birthday, NOW()) AS age_in_seconds 
FROM 
    table_name 
相關問題