我是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插入此查询。我尝试使用union all和内部联接中的select但它不起作用(可能结构错误)
这是我需要添加的查询。此查询显示每个用户的下载文档数,其中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;
我用什么来正确使用它?
答案 0 :(得分:0)
您可以加入子查询。
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
答案 1 :(得分:0)
有几种方法可以做到这一点。一种方法是将其添加到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. */