MySQL有一个名为
我想从一个包含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
感谢
我认为您可以使用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
结果应该是一样的,也许它们的性能不同,我不知道
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
并将第三字段添加到CCD_ 6。
我可以在您的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
select
greatest(isnull(column1,0),isnull(column2,0),isnull(column3,0))
如果每个列为空,则上面的查询将检查该列。如果该值为null,则将采用值0。然后它将为您提供最大值