我有一个用于记录Facebook应用程序用户操作的表。我想获取不超过9分钟的特定操作ID的最新行。该表有很多其他统计信息列,因此我仅显示代表问题的两行:
timestamp facebookID producerID eventID actionID numOfTickets
2012-05-28 13:16:38 100003286974944 9 1741 cpf 2
2012-05-28 13:16:13 100003286974944 9 1741 cpf 4
我想做的是获取最新行
actionID = 'cpf'
。我试过的是:
SELECT CONCAT_WS(' ', y.firstName, y.lastName) as fullName, x.facebookID, x.numOfTickets, MAX(x.timestamp)
FROM E4S_ANALYTICS.e4s_analytic_data x INNER JOIN E4S_FB.e4s_user_details y ON x.facebookID = y.facebookID
WHERE (x.actionID = 'CPF' AND x.numOfTickets > 0 AND x.producerID = 9 AND TIMEDIFF(NOW() , x.timestamp) < '00:09:00'
AND x.facebookID IN (SELECT facebookID FROM E4S_FB.e4s_session_data WHERE
TIMEDIFF(NOW() , sessionStart) < '00:09:00' ))
查询的结果是:
facebookID numOfTickets MAX(x.timestamp)
100003286974944 4 2012-05-28 13:16:38
返回的时间戳是正确的,但
numOfTickets
是4而不是2。需要注意的是,内部查询:
SELECT facebookID FROM E4S_FB.e4s_session_data
WHERE TIMEDIFF(NOW() , sessionStart) < '00:09:00' ))
用于查看谁仍在登录该应用程序。
最佳答案
SELECT CONCAT_WS(' ', y.firstName, y.lastName) AS fullName,
x.facebookID,
x.numOfTickets,
x.timestamp
FROM (
SELECT *
FROM E4S_ANALYTICS.e4s_analytic_data
WHERE actionID = 'cpf'
AND numOfTickets > 0
AND producerID = 9
AND TIMEDIFF(NOW() , timestamp) < '00:09:00'
AND (facebookID, timestamp) IN (
SELECT facebookID, MAX(timestamp)
FROM E4S_ANALYTICS.e4s_analytic_data
WHERE actionID = 'cpf'
AND numOfTickets > 0
AND producerID = 9
AND TIMEDIFF(NOW() , timestamp) < '00:09:00'
AND facebookID IN (
SELECT facebookID
FROM E4S_FB.e4s_session_data
WHERE TIMEDIFF(NOW() , sessionStart) < '00:09:00'
)
GROUP BY facebookID
)
) AS x
INNER JOIN E4S_FB.e4s_user_details AS y USING (facebookID)