Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 无法通过子查询获取数据(没有直接关系的多个子查询)_Mysql_Sql_Subquery - Fatal编程技术网

Mysql 无法通过子查询获取数据(没有直接关系的多个子查询)

Mysql 无法通过子查询获取数据(没有直接关系的多个子查询),mysql,sql,subquery,Mysql,Sql,Subquery,我想从包含以下字段的用户登录表中获取数据: 用户登录:id、状态、日期、用户id 在此表中,状态可以是1或2 如果状态为1,则登录或注销 我想在一行中获取登录和注销这两个详细信息我尝试了此查询: 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

我想从包含以下字段的用户登录表中获取数据:

用户登录:id、状态、日期、用户id

在此表中,状态可以是1或2

如果状态为1,则登录或注销

我想在一行中获取登录和注销这两个详细信息我尝试了此查询:

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.
当登录和注销都有数据时,我会得到数据。但我也希望当只有登录有数据,但没有注销


请帮我解决这个问题。

使用
左连接。像这样:

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

我以前尝试过这个方法,但没有获取数据,因为我没有使用MAX()。你能告诉我为什么我们需要使用MAX()。是的,谢谢你,这两个查询都很好,第二个更好,因为你必须为status=1和status=2分别设置一行。如果使用max,则只需选择max状态为1和状态为2的行。