查询内部查询返回"作为列"

时间:2017-01-17 09:16:58

标签: sql select count mariadb

我想列出表格中的所有公司以及每个特定公司的管理员数量。

表格:

companies
id
name
...

users
id
company_id
...

groups ('id' = 1 has 'name' = admin)
id
name 

users_groups
id
user_id
group_id

列出所有'公司'我写这个:

SELECT companies.name
FROM companies

获取' admin'在一个特定的公司'(具有给定的ID)我写这个

SELECT COUNT (users.id) 
FROM users, companies, users_groups WHERE
users.company_id = companies.id AND 
users_groups.user_id = users.id AND
users_groups.group_id = 1

那么如何合并这两个问题呢?这失败了:

SELECT 
  companies.name, 
    (
      SELECT COUNT (users.id) 
      FROM users, companies, users_groups WHERE
      users.company_id = companies.id AND 
      users_groups.user_id = users.id AND
      users_groups.group_id = 1
    ) 
  as admins_in_company
FROM users, companies, users_groups

2 个答案:

答案 0 :(得分:1)

使用显式连接语法和计数(distinct ...):

select c.name, count(distinct u.id)
from companies c
inner join users u
  on u.company_id = c.id
inner join users_groups ug
  on ug.user_id = u.id
where ug.group_id = 1
group by c.name

适用于所有公司:

select c.name, count(distinct u.id)
from companies c
left join users u
  on u.company_id = c.id
left join users_groups ug
  on ug.user_id = u.id
  and ug.group_id = 1
group by c.name

答案 1 :(得分:0)

SELECT c.name, COUNT(DISTINCT u.id) AS num_admins
    FROM groups AS g
    JOIN users_groups AS ug   ON ug.group_id = g.id
    JOIN users AS u           ON u.id = ug.user_id
    JOIN companies AS c       ON c.id = u.company_id
    WHERE g.group_id = 1
      AND g.name = 'admin'
    GROUP BY u.company_id;

目前还不清楚您是需要COUNT(DISTINCT u.id)还是COUNT(*)

我按照他们将要查看的顺序列出了4个表。 (这不是一项要求,但可以让用户更轻松地阅读和思考。)首先是groups,其中包含所有'过滤( WHERE ). Then it moves through the other tables all the way to getting the公司.name . Then the GROUP BY and its COUNT(DISTINCT ...)`已应用。

许多提示:许多架构(users_groups)设计:http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

groups - group_id and group.name are in a 1:1 relationship, yes? If you know that it is group_id = 1 , you can get rid of the table个群组completely from the query. If not, then be sure to have INDEX(姓名)`。