PHP / Mysqli - GROUP BY获取最新记录,但仅限于某些记录

时间:2017-05-16 16:08:02

标签: php mysqli group-by

我将此查询运行到GROUP BY session_id并获取最新(时间)记录:

$query = "SELECT type, session_id, session_name, session_email, time
FROM chat
WHERE time IN (
    SELECT MAX(time)
    FROM chat
    GROUP BY session_id
)
ORDER BY time DESC";

然而,我只想要最新的类型和时间记录。我怎样才能获得session_id,session_name,session_email的第一条记录?

1 个答案:

答案 0 :(得分:0)

    $query = "
    SELECT type, session_id, session_name, session_email, time
    FROM chat
    WHERE time IN
    (
        SELECT MAX(time)
        FROM chat
        GROUP BY session_id
    )
    ORDER BY time DESC
    LIMIT 5 /* gives you the first 5 records

    UNION

    SELECT type, session_id, session_name, session_email, time
    FROM chat
    WHERE time IN
    (
        SELECT MAX(time)
        FROM chat
        GROUP BY session_id
    )
    ORDER BY time ASC
    LIMIT 5 /* gives you the first 5 records in other sequence
    ";