查询内部查询返回 "as a column"

Query inside query returned "as a column"

我喜欢在 table 中列出所有公司以及每个特定公司拥有的管理员数量。

tables:

companies
id
name
...

users
id
company_id
...

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

users_groups
id
user_id
group_id

要列出所有 'companies' 我这样写:

SELECT companies.name
FROM companies

为了在一个特定的 'company'(具有给定的 id)中获得 'admin' 的数量,我写了这个

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

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

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
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 个 table。 (这不是必需的,但可以让用户更容易阅读和思考它。)首先是 groups,它具有所有的过滤(WHERE). Then it moves through the other tables all the way to getting thecompany.name. Then theGROUP BYand itsCOUNT(DISTINCT...)` 被应用。

关于 many:many 架构 (users_groups) 设计的提示:http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

groups -- group_idandgroup.nameare in a 1:1 relationship, yes? If you know that it isgroup_id = 1, you can get rid of the tablecompletely from the query. If not, then be sure to have table.

中的 INDEX(name)`