SQL连接或子选择总组合匹配

时间:2013-07-06 04:41:23

标签: sql sql-server

我的表名为:

  • 用户
  • userAccount
  • userRight

与1对多的关系。

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

例如:

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

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

a 6
c 5
b 2

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

1 个答案:

答案 0 :(得分: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

如果你想将total total用于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