简体   繁体   English

3个表的MySQL连接-从2个子表中获取合计值

[英]MySQL join of 3 tables - get aggregate value from 2 child tables

I need to create a summary from 3 different tables, 1 parent table, 2 child tables. 我需要从3个不同的表,1个父表,2个子表创建一个摘要。

How can I get the number of records from two child tables, based on the user id (pk in each of the 3 tables). 如何根据用户ID(3个表中的每个表中的pk)从两个子表中获取记录数。

Parent table ( user ) pk is userId Child tables 1 and 2 have composite pks of userId and webId. 父表( user )pk是userId子表1和2具有userId和webId的组合pks。

I know this isn't the proper SQL syntax, but it illustrates what I'm after. 我知道这不是正确的SQL语法,但是它说明了我的追求。

select u.userId, count(table1.webId), count(table2.webId)
from `user` u 
left join `table1` t1 on u.userId = t1.userId
left join `table2` t2 on u.userId = t2.userId
group by u.userId

You might need to add DISTINCT - 您可能需要添加DISTINCT

SELECT u.userId, COUNT(DISTINCT table1.webId), COUNT(DISTINCT table2.webId)
FROM `user` u 
LEFT JOIN `table1` t1
    ON u.userId = t1.userId
LEFT JOIN `table2` t2
    ON u.userId = t2.userId
GROUP BY u.userId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM