如何在MySql中选择今天之前的最新日期?

时间:2017-07-12 03:24:57

标签: mysql sql

如何选择今天之前有最新日期的记录? 例如,我有两个日期的多个记录(例如2017-07-10)。那么我有更多其他日期的记录(例如2017-07-09,2017-07-08 ......)。

现在我要选择日期为2017-07-10的所有记录。我不希望其他日期如09,08,07。仅在今天之前选择最新日期。我怎么能这样做?

SELECT
    AR.ID, mR.Description, AR.ActualReading 
FROM 
    machines M 
    INNER JOIN machinemeterreadinglist mRM 
        ON mRM.MachineID = M.ID 
    INNER JOIN meterreadingdescription mR 
        ON mR.ID = mRM.MeterReadingID 
    INNER JOIN actualmeterreading AR 
        ON AR.MachineMeterReadingId = mRM.ID 
    INNER JOIN meterreadingrecords mRec 
        ON mRec.ActualMeterReadingID = AR.ID 
WHERE 
    M.ID = '4364616d-8cff-4507-9dae-be4be8aee1f5' 
    AND mRec.rDate < CURRENT_DATE() 
LIMIT 
    1 ;

2 个答案:

答案 0 :(得分:0)

也许你可以比较昨天的日期:

SELECT AR.ID, mR.Description, AR.ActualReading
FROM machines M INNER Join
     machinemeterreadinglist mRM
     ON mRM.MachineID = M.ID inner Join
     meterreadingdescription mR
     ON mR.ID = mRM.MeterReadingID inner Join
     actualmeterreading AR
     ON AR.MachineMeterReadingId = mRM.ID inner join
     meterreadingrecords mRec
     ON mRec.ActualMeterReadingID = AR.ID
where M.ID = '4364616d-8cff-4507-9dae-be4be8aee1f5' AND
       mRec.rDate = CURRENT_DATE() - INTERVAL 1 DAY;

答案 1 :(得分:0)

你可以重构你的WHERE子句,放置LIMIT,因为你想要所有一个特定日期的记录而不只是一个(我想):

SELECT
    AR.ID, mR.Description, AR.ActualReading 
FROM 
    machines M 
    INNER JOIN machinemeterreadinglist mRM 
        ON mRM.MachineID = M.ID 
    INNER JOIN meterreadingdescription mR 
        ON mR.ID = mRM.MeterReadingID 
    INNER JOIN actualmeterreading AR 
        ON AR.MachineMeterReadingId = mRM.ID 
    INNER JOIN meterreadingrecords mRec 
        ON mRec.ActualMeterReadingID = AR.ID 
WHERE 
    M.ID = '4364616d-8cff-4507-9dae-be4be8aee1f5' 
    AND mRec.rDate =
    (
    SELECT
        -- latest date with available data before today
        MAX(mRed.rDate)
    FROM
        -- same joined tables as original query
        machines M 
        INNER JOIN machinemeterreadinglist mRM 
            ON mRM.MachineID = M.ID 
        INNER JOIN meterreadingdescription mR 
            ON mR.ID = mRM.MeterReadingID 
        INNER JOIN actualmeterreading AR 
            ON AR.MachineMeterReadingId = mRM.ID 
        INNER JOIN meterreadingrecords mRec 
            ON mRec.ActualMeterReadingID = AR.ID
    WHERE
         -- same condition as original query
         M.ID = '4364616d-8cff-4507-9dae-be4be8aee1f5' 
         AND mRec.rDate < CURRENT_DATE()      
    ) ;

您可以在 dbfiddle here

检查您的方案模拟

旁注:您的五表结构可能会简化,JOIN对我来说很奇怪。我试图从它们中重现你的结构。