我需要在不同的表中从一堆不同的日期获取MAX日期。我有一个查询返回6个日期。我需要以某种方式获得该查询的最大值。这是我的第一个查询,它提供了6个不同的MAX日期:
SELECT
MAX(mi.last_updated_dts),
(SELECT MAX(lt.created_dts) FROM live_training as lt WHERE lt.me_id = 1156),
(SELECT MAX(gm.created_dts) FROM group_member as gm WHERE gm.me_id = 1156),
(SELECT MAX(clm.created_dts) FROM contact_list_member as clm WHERE clm.me_id = 1156),
(SELECT MAX(mc.created_dts) FROM member_case as mc WHERE mc.me_id = 1156),
(SELECT MAX(mcc.created_dts) FROM member_case_comment as mcc INNER JOIN member_case as mc ON (mcc.member_case_id = mc.id) WHERE mc.me_id = 1156)
FROM
member_info AS mi
WHERE mi.id = 1276
这是我正在尝试做的事情,但它不起作用:
SELECT MAX(
SELECT
MAX(mi.last_updated_dts),
(SELECT MAX(lt.created_dts) FROM live_training as lt WHERE lt.me_id = 1156),
(SELECT MAX(gm.created_dts) FROM group_member as gm WHERE gm.me_id = 1156),
(SELECT MAX(clm.created_dts) FROM contact_list_member as clm WHERE clm.me_id = 1156),
(SELECT MAX(mc.created_dts) FROM member_case as mc WHERE mc.me_id = 1156),
(SELECT MAX(mcc.created_dts) FROM member_case_comment as mcc INNER JOIN member_case as mc ON (mcc.member_case_id = mc.id) WHERE mc.me_id =1156)
FROM
member_info AS mi
WHERE mi.id = 1276
) as theMostMaxDate
我不知道在声明中放什么,或者甚至可能。谢谢你的帮助!
答案 0 :(得分:2)
一个解决方案可能是重写查询以在派生表中使用union all
并从中获取最大值,尽管这只会得到一个日期而没有关于它的来源的信息(但如果是重要的是,您可以添加一个文字值列,指示哪个查询为您提供了最大日期):
SELECT MAX(max_date)
FROM (
SELECT MAX(mi.last_updated_dts) AS max_date FROM member_info AS mi WHERE mi.id = 1276
UNION ALL
SELECT MAX(lt.created_dts) FROM live_training as lt WHERE lt.me_id = 1156
UNION ALL
SELECT MAX(gm.created_dts) FROM group_member as gm WHERE gm.me_id = 1156
UNION ALL
SELECT MAX(clm.created_dts) FROM contact_list_member as clm WHERE clm.me_id = 1156
UNION ALL
SELECT MAX(mc.created_dts) FROM member_case as mc WHERE mc.me_id = 1156
UNION ALL
SELECT MAX(mcc.created_dts) FROM member_case_comment as mcc
INNER JOIN member_case as mc ON (mcc.member_case_id = mc.id) WHERE mc.me_id = 1156
) t
答案 1 :(得分:0)
Max()是按功能分组,适用于单个字段或表达式。改为使用greates()函数,它适用于多个字段或表达式。
SELECT
GREATEST(MAX(mi.last_updated_dts),
(SELECT MAX(lt.created_dts) FROM live_training as lt WHERE lt.me_id = 1156),
(SELECT MAX(gm.created_dts) FROM group_member as gm WHERE gm.me_id = 1156),
(SELECT MAX(clm.created_dts) FROM contact_list_member as clm WHERE clm.me_id = 1156),
(SELECT MAX(mc.created_dts) FROM member_case as mc WHERE mc.me_id = 1156),
(SELECT MAX(mcc.created_dts) FROM member_case_comment as mcc INNER JOIN member_case as mc ON (mcc.member_case_id = mc.id) WHERE mc.me_id = 1156)) as maxdate
FROM
member_info AS mi
WHERE mi.id = 1276
另一种解决方案是将独立查询与union结合使用,您可以使用max()从结果集中选择总体最大值。
答案 2 :(得分:0)
@jpw有针对此问题的正确解决方案。我只想指出你可以在没有子查询的情况下做到这一点:
403 forbidden error