mysql: 将子查询添加到现有查询

mysql: add subquery to existing query

我是sql的新手,在实习期间我被要求了解一些sql所以我开始学习并被允许在测试环境中练习(没有更新,插入或删除但仅显示),在练习时我有这个问题,这是我现有的查询:

Select 
ab.USER_ID,
user.email AS email, 
concat(user.firstName, ' ' ,user.lastName ) AS name, 
usl.loginDateTime AS LastLogin,
ab.creation_time AS DateJoined,
udl.devicePlatform AS Devices,
user.status AS Status
FROM F_USR_USER AS user

INNER JOIN F_USR_ACCOUNT_BASE AS ab 
on user.ID= ab.USER_ID

INNER JOIN F_USR_DSL_LOG AS udl
ON ab.USER_ID=udl.USER_ID

INNER JOIN F_USR_SESSION_LOG AS usl
ON ab.USER_ID=usl.USER_ID
group by ab.USER_ID

我想将这个 select 插入到这个 query.I 中尝试使用 union all 和内部连接中的 select 但它没有用(可能结构错误)

这是我需要的查询 add.This 查询显示每个用户的下载文档数 User_id 作为我在此查询中使用的所有表的外键。

Select ab.user_id,count(*) as total
 from F_USR_ACCOUNT_BASE AS ab ,F_USR_DOCUMENT AS doc
 where ab.USER_ID= doc.USER_ID and doc.extractionComplete = '1'
 group by ab.user_ID;

我用什么来正确获取它?

您可以加​​入子查询。

Select 
    ab.USER_ID,
    user.email AS email, 
    concat(user.firstName, ' ' ,user.lastName ) AS name, 
    usl.loginDateTime AS LastLogin,
    ab.creation_time AS DateJoined,
    udl.devicePlatform AS Devices,
    user.status AS Status,
    doc.total AS TotalDocs
FROM F_USR_USER AS user

INNER JOIN F_USR_ACCOUNT_BASE AS ab 
    on user.ID= ab.USER_ID

INNER JOIN F_USR_DSL_LOG AS udl
    ON ab.USER_ID=udl.USER_ID

INNER JOIN F_USR_SESSION_LOG AS usl
ON ab.USER_ID=usl.USER_ID

INNER JOIN (
    Select user_id, count(*) as total
    from F_USR_DOCUMENT
    where extractionComplete = '1'
    group by user_ID) AS doc
) ON doc.user_id = ab.user_id

group by ab.USER_ID

有几种方法可以做到这一点。一种方法是将其添加到 select 子句中:

Select 
ab.USER_ID,
user.email AS email, 
concat(user.firstName, ' ' ,user.lastName ) AS name, 
usl.loginDateTime AS LastLogin,
ab.creation_time AS DateJoined,
udl.devicePlatform AS Devices,
user.status AS Status,
(
    Select  count(*) as total
    from    F_USR_DOCUMENT AS doc
    where   ab.USER_ID= doc.USER_ID 
    and     doc.extractionComplete = '1'
) as totalDocs
From
F_USR_USER AS user
INNER JOIN 
F_USR_ACCOUNT_BASE AS ab on 
    user.ID= ab.USER_ID
INNER JOIN 
F_USR_DSL_LOG AS udl ON 
    ab.USER_ID=udl.USER_ID
INNER JOIN 
F_USR_SESSION_LOG AS usl ON 
    ab.USER_ID=usl.USER_ID
group by ab.USER_ID /* Maybe take this GROUP BY out.  WHERE clause to filter. */