[英]join count from one table to select from another - mysql
I have a select query with a subquery in it on table a: 我在表a上有一个带有子查询的选择查询:
select UserName, Name, anniversaryDate, RegionCode
from a where UserName in
(
select Username from
(
select Username, max(timeUsed)
from log_table where role='Cou'
group by Username order by max(timeUsed) desc limit 10
) a
)
which works fine, now I have another table called b, on that table I only have 3 columns: 它工作正常,现在我有另一个表b,该表上只有3列:
UserName, PName and feedback 用户名,PName和反馈
which have each UserName multiple times and I want to join to my first query the count of each UserName I got from the first query. 其中每个用户名都有多次,我想加入我的第一个查询,我从第一个查询中获得的每个用户名的计数。
for eaxmple: 对于eaxmple:
SELECT COUNT(UserName) FROM b where UserName='Admin' group by UserName
How do I join the results from the second query to the first one? 如何将第二个查询的结果加入第一个查询?
Tables: 表:
log_table : log_table:
id - Int, AI, PK id-Int,AI,PK
Username - varchar 用户名-varchar
Action - Int 动作-内部
timeUsed - Datetime timeUsed-日期时间
role - varchat 角色-varchat
a: A:
UserName - varchar, PK 用户名-varchar,PK
Name - varchar 名称-varchar
anniversaryDate - Datetime 周年纪念日-日期时间
RegionCode - Int RegionCode-整数
b: b:
UserName - varchar 用户名-varchar
PName - varchar PName-varchar
feedback - varchar 反馈-varchar
Based on your table structure the query below might add the necessary column you are looking for: 根据您的表结构,以下查询可能会添加您要查找的必要列:
select users.UserName, Name, anniversaryDate, RegionCode,
Coalesce(count(b.UserName),0) as cnt
from users
left outer join (select Username, max(timeUsed)
from log_table where role='Cou'
group by Username order by max(timeUsed) desc limit 10
) a using (UserName)
left outer join fedbacks b on (a.UserName = b.userName)
group by users.UserName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.