gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:41 26 4
gpt4 key购买 nike

我需要从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com