PHP MySQL从结果组中选择MAX()

时间:2011-07-29 04:19:02

标签: php mysql

我有一个我正在努力解决的MySQL查询,我似乎无法使其正常工作。

这是它的样子:

SELECT 
    DISTINCT reminders.recordID 
FROM 
    reminders, 
    (SELECT 
        DISTINCT recordID, 
        MAX(date) as MaxDate 
     FROM reminders 
     GROUP BY recordID
    ) dts 
WHERE 
    reminders.owner = '$owner'
    AND reminders.date = dts.MaxDate

我需要在表格中提醒所有提醒(提醒),例如recordID 14.然后我需要从该组结果中选择最近的日期(MAX())并返回recordID具有最近的日期,但不超过特定日期(WHERE date <= '$date')。

有人对我如何解决这个问题有任何想法吗?

1 个答案:

答案 0 :(得分:1)

怎么样......

SELECT recordID, date
FROM reminders
WHERE owner = $owner
AND date <= $date
ORDER BY date DESC
LIMIT 1

...哦,我想我现在看到:“每个ID可能会附加一些提醒”清除了一些内容。所以可能有一个更优雅的解决方案,但我猜这将工作:

    SELECT DISTINCT r1.recordID,
        (SELECT r2.date
            FROM reminders as r2
            WHERE r2.owner = $owner
            AND r2.date <= $date
            AND r2.recordID = r1.recordID
            ORDER BY r2.date DESC
            LIMIT 1) as maxDate
    FROM reminders as r1
    WHERE r1.owner = $owner
    AND r1.date <= $date