我想从3个日期字段之间的数据库中获取latest_date
。
现在我使用以下查询,但它不适合我的要求。
如何比较3日期字段以获取latest_date
?
SELECT DISTINCT e.id, MAX( cc.updated ) AS clinicComment_date, MAX( af.created ) AS attenderInfo_created, e.updated AS event_updated,
(
CASE
WHEN MAX( cc.updated ) > MAX( af.created )
THEN MAX( cc.updated )
WHEN MAX( cc.updated ) < MAX( af.created )
THEN MAX( af.created )
ELSE e.updated
END
) AS latest_date
FROM Event e
LEFT JOIN EventClinic ec ON e.id = ec.event_id
LEFT JOIN ClinicComment cc ON ec.clinic_id = cc.clinic_id
LEFT JOIN AttendersInfo af ON af.event_id = e.id
WHERE e.status = 'active'
AND (
e.id =43
OR e.id =45
)
GROUP BY e.title
ORDER BY latest_date DESC
由于
答案 0 :(得分:1)
我认为您可以使用GREATEST()
功能
GREATEST(cc.updated, af.created, e.updated) AS latest_date
这个应该为您提供单行的最新日期
如果您想要所有行之间的最新信息:
MAX(GREATEST(cc.updated, af.created, e.updated)) AS latest_date
与
相同GREATEST(MAX(cc.updated), MAX(af.created), MAX(e.updated)) AS latest_date
要处理NULL值,您可以使用COALESCE
GREATEST(
COALESCE(MAX(cc.updated), 0),
COALESCE(MAX(af.created), 0),
COALESCE(MAX(e.updated), 0)
) AS latest_date
或者
MAX(
GREATEST(
COALESCE(cc.updated), 0),
COALESCE(af.created), 0),
COALESCE(e.updated), 0)
)) AS latest_date
结果应该是相同的,也许它们的性能不同,我不知道
答案 1 :(得分:0)
MySQL有一个名为GREATEST()
的功能。你可以替换
(
CASE
WHEN MAX( cc.updated ) > MAX( af.created )
THEN MAX( cc.updated )
WHEN MAX( cc.updated ) < MAX( af.created )
THEN MAX( af.created )
ELSE e.updated
END
) AS latest_date
使用GREATEST(MAX(cc.updated), MAX(af.created)) AS latest_date
并添加第三个字段。
答案 2 :(得分:0)
我可以在Case语句中看到不满足每个条件的问题。 Mysql提供GREATEST函数来返回最大值
试试这个
select DISTINCT e.id,GREATEST(MAX( cc.updated ),MAX( af.created ),e.updated) as Latest_Date
FROM Event e
LEFT JOIN EventClinic ec ON e.id = ec.event_id
LEFT JOIN ClinicComment cc ON ec.clinic_id = cc.clinic_id
LEFT JOIN AttendersInfo af ON af.event_id = e.id
WHERE e.status = 'active'
AND ( e.id =43 OR e.id =45 )
GROUP BY e.title
ORDER BY latest_date DESC