我有一个这样的表,用于保存用户登录和注销时间:
----------------------------------------------
name |date |timestamp |action
----------------------------------------------
Philip |2017-05-08 |1494225926 |login
Anna |2017-05-08 |1494229108 |login
Laura |2017-05-08 |1494232336 |login
Gerry |2017-05-08 |1494232431 |login
Anna |2017-05-08 |1494243781 |logout
Anna |2017-05-08 |1494246660 |login
Laura |2017-05-08 |1494247039 |logout
Philip |2017-05-08 |1494248271 |logout
Laura |2017-05-08 |1494249980 |login
Philip |2017-05-08 |1494252177 |login
Laura |2017-05-08 |1494255182 |logout
Laura |2017-05-08 |1494256117 |login
Anna |2017-05-08 |1494259279 |logout
Philip |2017-05-08 |1494262771 |logout
Philip |2017-05-08 |1494262775 |login
Gerry |2017-05-08 |1494262821 |logout
Laura |2017-05-08 |1494262822 |logout
Philip |2017-05-08 |1494262886 |logout
我试图创建一个查询,告诉我谁在时间戳指定的时间登录(即1494248400)..任何想法?
答案 0 :(得分:0)
您可以使用NOT IN
,例如:
SELECT * FROM test WHERE action = 'login' and `timestamp` <= 1494248400
AND name NOT IN (
SELECT name FROM test WHERE action = 'logout' and `timestamp` <= 1494248400
)
这里是 SQL Fiddle 。
<强>更新强>
要让所有注销但又重新登录的用户,您可以使用GROUP BY
条件,例如:
SELECT * FROM (
SELECT name, max(`timestamp`) as ts
FROM test WHERE action = 'login' and `timestamp` <= 1494248400
GROUP BY name ) t1
WHERE t1.name NOT IN (
SELECT name FROM test WHERE action = 'logout'
AND `timestamp` <= 1494248400 AND timestamp >= t1.ts
);
此处有更新的 SQL Fiddle 。