我需要从 3 个不同的表(1 个父表和 2 个子表)创建一个摘要。
如何根据用户 ID(3 个表中的每个表中的 pk)从两个子表中获取记录数。
父表(user
)pk为userId
子表 1 和 2 具有 userId 和 webId 的复合 pks。
我知道这不是正确的 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
最佳答案
您可能需要添加 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
关于MySQL 连接 3 个表 - 从 2 个子表中获取聚合值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9793423/