0

我有名为:

  • 用户
  • 用户帐号
  • 用户权利

有一对多的关系。

我正在寻找的是一个查询,它将为我提供帐户和权利的总数。

例如:

user: a
account: 1, 2, 3
right: a, b, c

user b
account: 1, 2
right: 

user c:
account: 1
right: e, f, g, h

应该返回按 count 降序排列的结果

a 6
c 5
b 2

我使用连接和分组将其关闭,但我最终得到 a: 9 作为它获得 3 x 3 记录。

4

1 回答 1

2

尝试关注一个

SELECT user_name,(SELECT COUNT(*) FROM userRight WHERE user_id=u.user_id) + 
(SELECT COUNT(*) FROM userAccount WHERE user_id=u.user_id) AS total 
FROM user u ORDER BY total DESC

如果您想将用户总数放入 where 子句中,那么

SELECT user_name,(SELECT COUNT(*) FROM userRight WHERE user_id=u.user_id) + 
(SELECT COUNT(*) FROM userAccount WHERE user_id=u.user_id) AS total 
FROM user u WHERE ((SELECT COUNT(*) FROM userRight WHERE user_id=u.user_id) + 
(SELECT COUNT(*) FROM userAccount WHERE user_id=u.user_id))>10 ORDER BY total DESC
于 2013-07-06T04:53:10.753 回答