我有一个应用,我希望用户输入工作历史记录。我使用DATE格式(每个作业的start_date和end_date)将结果存储在mysql表中。因此,例如,在几个条目之后它可能看起来像这样(job_history表:
Job Start End
Dishwasher 2013-07-10 2014-03-28
Banker 2014-04-02 2014-10-10
Cahsier 2014-10-11 2014-12-20
我正在尝试设置一个mysql查询,该查询将检查特定年份是否有任何丢失的天数。对于我们的示例,请使用2014. 2014-03-29至2014-04-01期间缺少天数。
通过搜索,我找不到任何好的例子。我认为有一个更好的方法来做这个比做一个PHP循环和做365个查询(哎哟!)。感谢
编辑:更新了包含年末和年末的示例:
Job Start End
Dishwasher 2013-07-10 2013-12-01
Banker 2014-01-10 2014-10-10
Cahsier 2014-10-11 2014-12-20
在这个例子中,我们的输入年份将是2014年,我们将在年初的9天内被发现,而在年底则有11天。
答案 0 :(得分:1)
对于后来提出这个问题的人来说,最初的答案就是这个
SELECT jh.id,
CASE
WHEN datediff(jh1.start, jh.end) > 1
THEN datediff(jh1.start, jh.end)
ELSE NULL
END as DifferenceInDays
FROM job_history jh
LEFT JOIN job_history jh1 ON jh1.id = (jh.id + 1)
这样做是假设自连接的顺序ID,这样您可以将最后一行日期与当前行日期进行比较。
在对要求进行了大量补充之后,这将满足您的需求。
SELECT position, id, DifferenceInDays
FROM
( SELECT 'BEGINNING' as position, id,
@a := if(@a = 'BAD', 'BAD', if(DATE(concat(year(now()), '-01-01')) BETWEEN start AND end, 'BAD', '')),
case
WHEN @a = 'BAD'
THEN NULL
ELSE datediff(jstart, DATE(concat(year(now()), '-01-01')))
end AS DifferenceInDays
FROM
( SELECT jh.*, jh3.start as jstart
FROM job_history jh
CROSS JOIN(SELECT @a:='')t
LEFT JOIN (SELECT min(start) as start FROM job_history where userid = 123456 AND YEAR(start) = YEAR(NOW())) jh3 ON jh3.start = jh.start
WHERE jh.userid = 123456
ORDER BY id
)t
UNION ALL
SELECT 'MIDDLE', jh.id, '',
case
WHEN datediff(jh1.start, jh.end) > 1
THEN datediff(jh1.start, jh.end) - 1
ELSE NULL
end as DifferenceInDays
FROM
( SELECT *, @new_id := @new_id + 1 as new_id
FROM job_history, (select @new_id := 0) temp
WHERE userid = 123456
) jh
LEFT JOIN
( SELECT *, @new_id1 := @new_id1 + 1 as new_id
FROM job_history, (select @new_id1 := 0) temp
WHERE userid = 123456
) jh1 ON jh1.new_id = (jh.new_id + 1)
UNION ALL
SELECT 'ENDING', id,
@b := if(@b = 'BAD', 'BAD', if(DATE(concat(year(now()), '-12-31')) BETWEEN start AND end, 'BAD', '')),
case
WHEN @b = 'BAD'
THEN NULL
ELSE datediff(DATE(concat(year(now()), '-12-31')), jend)
end
FROM
( SELECT jh.*, jh2.end as jend
FROM job_history jh
CROSS JOIN(SELECT @b:='')t
LEFT JOIN (SELECT max(end) as end FROM job_history WHERE userid = 123456) jh2 ON jh2.end = jh.end
WHERE jh.userid = 123456
ORDER BY id
)t
ORDER BY case position WHEN 'BEGINNING' THEN 1 WHEN 'MIDDLE' THEN 2 ELSE 3 END ASC, id ASC
) t
WHERE DifferenceInDays IS NOT NULL
答案 1 :(得分:-2)
您可date_diff用于查找两个日期之间的差异
$interval = date_diff($datetime1, $datetime2);