我希望GROUP BY选择最早的StartSessionTime然后我想基于StartSessionTime进行过滤,我尝试了各种各样的东西,最近的是:
$sql_d = "SELECT a.* FROM Session_Log a INNER JOIN
( SELECT ID, MIN(SessionStartTime)
FROM Session_Log GROUP BY ID
) b
ON a.ID = b.ID
AND a.SessionStartTime = b.SessionStartTime
WHERE DATE(SessionStartTime) < ( '2018-01-01' + INTERVAL $b DAY )
AND DATE(SessionStartTime) >= ( '2018-01-01' + INTERVAL $a DAY )";
请帮助正确表达
答案 0 :(得分:1)
您需要为MIN(SessionStartTime)
指定别名,以便在ON
子句中引用它。
SELECT a.*
FROM FMan_Session_Log AS a
JOIN (
SELECT DeviceID, MIN(SessionStartTime) AS MinSessionStartTime
FROM FMan_Session_Log
) AS b ON a.DeviceID = b.DeviceID AND a.SessionStartTime = b.MinSessionStartTime
WHERE a.SessionStartTime >= DATE_ADD('2018-01-01', INTERVAL $a DAY)
AND a.SessionStartTime < DATE_ADD('2018-01-01, INTERVAL $b DAY)
答案 1 :(得分:1)
修正了错误。首先没有为b定义SessionStartTime。其次,SessionStartTime在WHERE子句
中是不明确的$sql_d = "SELECT a.* FROM Session_Log a INNER JOIN
( SELECT ID, MIN(SessionStartTime) **as SessionStartTime**
FROM Session_Log GROUP BY ID
) b
ON a.ID = b.ID
AND a.SessionStartTime = b.SessionStartTime
WHERE DATE(a.SessionStartTime) < ( '2018-01-01' + INTERVAL $b DAY )
AND DATE(a.SessionStartTime) >= ( '2018-01-01' + INTERVAL $a DAY )";