我想从user_login表中获取包含以下字段的数据:
user_login:id,status,date,user_id
此表中的状态可以是1或2
如果status为1,则登录else logout。
我想在一行中登录并注销两个细节,我尝试了这个查询:
select login.date, logout.date from
(select date from user_login where userId = 1 and status = 1 and date = now()) login,
(select date from user_login where userId = 1 and status = 2 and date = now()) logout.
我在登录和注销都有数据时获取数据。但我也想要只有登录才有数据但不能退出。
请帮助我解决这个问题。
答案 0 :(得分:0)
使用LEFT JOIN
。像这样:
select login.date, logout.date
from
(
select
userId,
date
from
user_login where userId = 1 and status = 1 and date = now()
)
login
LEFT JOIN
(
select
date,
userId
from
user_login
where
status = 2
and date = now()
) logout
ON logout.userId=login.userId
或者我认为更好的解决方案是做这样的事情:
SELECT
user_login.userId,
MAX(CASE WHEN user_login.status=1 THEN date ELSE NULL END) AS loginDate,
MAX(CASE WHEN user_login.status=2 THEN date ELSE NULL END) AS logoutDate,
FROM
user_login
WHERE
user_login.userId=1
AND date = now()
GROUP BY
user_login.userId