【问题标题】:How many rows there are in a one to many relation?一对多关系中有多少行?
【发布时间】:2012-01-27 02:09:14
【问题描述】:

我在 MySQL 上有两个表,结构如下:

用户: 编号 |名字

帐户: 编号 |用户名 |金额

我需要一个查询来获取每个用户的帐户总数,结果中也包含用户名。有没有办法做到这一点?我在 from 子句中尝试过子查询,但我不知道如何使用连接来实现这一点,但我怀疑这是否可能是解决方案......有什么想法吗?

这是我假装得到的示例数据和示例输出:

Users
1 | 'John'
2 | 'Peter'

Accounts
1 | 1 | 1000
2 | 1 | 2000
3 | 2 | 1500

query:
'John'  | 2  <- there are 2 accounts for user 'John'
'Peter' | 1  <- there is only 1 account for user 'Peter'

另外,如果我希望获得更多关于我的结果的汇总数据怎么办?说......总金额。例如:

another query:
'John'  | 2 | 3000 <- 2 accounts for John, which sums 3000
'Peter' | 1 | 1500 <- 1 account for Peter, which sums 1500

【问题讨论】:

  • 看看 INNER JOIN、GROUP BY 和 SUM()

标签: mysql sql one-to-many


【解决方案1】:

这里有一个查询来获取用户的姓名和他们的帐户数量:

SELECT u.name, COUNT(a.id) AS numAccounts
FROM Users u
LEFT JOIN Accounts a ON u.id=a.userid
GROUP BY u.id;

要获得金额列的总和,您可以执行以下操作:

SELECT u.name, COUNT(a.id) AS numAccounts, SUM(u.amount) AS totalAmount
FROM Users u
LEFT JOIN Accounts a ON u.id=a.userid
GROUP BY u.id;

【讨论】:

    【解决方案2】:
    select u.name, count(a.id) as numAccounts
    from
    users as u, accounts as a
    where u.id = a.userid
    group by u.id
    
    
    select u.name, count(a.id) as numAccounts, sum(a.amount) as totalAmount
    from
    users as u, accounts as a
    where u.id = a.userid
    group by u.id
    

    编辑:请注意,如果用户没有帐户,他们将不会出现在此处,并且您将需要像 Jonah 的查询一样的左连接。

    【讨论】:

    • 谢谢!似乎左连接的解决方案是一个;)
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2018-03-16
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多