从不同的日期时间字段中选择最新的日期时间

时间:2015-06-28 13:51:49

标签: mysql

不同的表中有不同的日期时间字段,我必须选择所有日期时间字段中的最新字段。表格是:

Question
--------
askedby
questionType
lastupdated

Document
----------
submittedBy
documentType
lastupdated

Instruction
-----------
submittedBy
instructionType
lastupdated

试图从

开始
SELECT Question.lastupdated,Document.lastupdated,Instruction.lastupdated
FROM Question,Document,Instruction
WHERE lastupdated=(select max(lastupdated))
ORDER BY lastupdated DESC

如果表中lastupdated的值为:

Question table:    2015-06-28 07:00:00
Document table:    2015-06-28 07:30:00
Instruction table: 2015-06-28 08:00:00

然后应该选择Instruction表中的值,例如2015-06-28 08:00:00

在这里,我必须从三个数据库中选择最新的lastupdated列。我是SQL查询的新手,不知道如何开始。

1 个答案:

答案 0 :(得分:0)

由于看起来你只想从三个析取集中提取最后一个日期,一个简单的选项就是对每个表使用一个查询,并使用union all从三个结果中选择一个并应用max到那套,像这样:

SELECT MAX(lastupdated) AS max_lastupdated
FROM 
(
    SELECT MAX(lastupdated) lastupdated FROM Question
    UNION ALL
    SELECT MAX(lastupdated) lastupdated FROM Document
    UNION ALL
    SELECT MAX(lastupdated) lastupdated FROM Instruction
) A

实际上你甚至不需要在三个select语句中选择最大值,只需获取lastupdated就足够了,尽管如果索引支持上面的查询可能会更快:

SELECT MAX(lastupdated) AS max_lastupdated
FROM 
(
    SELECT lastupdated FROM Question
    UNION ALL
    SELECT lastupdated FROM Document
    UNION ALL
    SELECT lastupdated FROM Instruction
) A

Sample SQL Fiddle