mysql查询带来3个表

时间:2016-05-13 15:36:02

标签: mysql count left-join

我一直在尝试从mysql DB中的3个表中获取多个计数值:

个人资料用户prof_opt选项
+ ------------- + + ------------------------ + + -------- ----------- + + --------------------------- +
| id |名字| | id |名字| id_prof | | id_prof | id_opt | | id |父母|名称|
+ ------------- + | ------------------------- + + ------- ------------ + + --------------------------- +
| 1 | dev | | 1 | user1 | 1 | | 1 | 100 | | 100 | null | m1 |
| 2 |管理员| | 2 | user2 | 3 | | 1 | 101 | | 101 | 100 | m1_a |
| 3 |基本的| | 3 | user3 | 3 | | 1 | 102 | | 102 | 100 | m1_b |
+ ------------- + + ------------------------ + | 1 | 200 | | 200 | null | m2 |
| 1 | 201 | | 201 | 200 | m2_a |
| 1 | 202 | | 202 | 200 | m2_a |
| 1 | 300 | | 300 | null | m3 |
| 1 | 301 | | 301 | 300 | m3_a |
| 3 | 300 | | 302 | 300 | m2_b |
| 3 | 301 | + --------------------------- +
| 3 | 302 |
+ ------------------- +

表选项包含使用选项和子选项动态构建用户菜单的数据,我没有包含保存文件名的列url,如:

- maintainers.php
-users.php
-profiles.php

想法是:

个人资料列表,每个个人资料的用户数量以及每个个人资料的选项数量

此查询获取个人资料和用户数量:

SELECT p.id, p.name, count(u.id_prof) AS nr_users
FROM profile p LEFT JOIN user u ON p.id = u.id_prof
GROUP BY p.id

这个其他查询得到 每个配置文件的配置文件和选项数量....

SELECT p.id, p.name, count(po.id_prof) AS nr_users
FROM profile p LEFT JOIN prof_opt po ON p.id = po.id_prof
GROUP BY p.id

但是如何将两个结果混合到一个查询中?

我试过这个,但是对每个配置文件的选项数量不起作用:

SELECT p.id, p.name, count(u.id_prof) AS nr_users, count(po.id_prof) AS nr_options
FROM profile p 
LEFT JOIN user u ON p.id = u.id_prof
LEFT JOIN prof_opt po ON u.id = po.id_prof
GROUP BY p.id, u.id_prof

我想要:

| id |名字| nr_users | nr_options |
| 1 | dev | 1 | 8 |
| 2 |管理员| 0 | 0 |
| 3 |基本的| 2 | 3 |

请问任何人都可以发布可以获得预期结果的查询,或者指出我的查询中缺少或错误的内容吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

一种选择是使用从属子查询来获取计数:

SELECT 
p.id,
p.name,
(SELECT COUNT(id) FROM user WHERE id_prof = p.id) as nr_users,
(SELECT COUNT(id) FROM prof_opt WHERE id_prof = p.id) as nr_options
FROM profile p
GROUP p.id

根据我的经验,从属子查询具有相当好的性能,并且通常比执行多个查询更快。我没有分析证据来证实我对他们表现的陈述,但我认为他们的表现非常好。

答案 1 :(得分:0)

SELECT 
  p.id, 
  p.name,
  u.u_count,
  o.opt_count
FROM  profile
LEFT JOIN (
  SELECT id_prof,
     COUNT(id) u_count
  FROM user
  GROUP BY id_prof
) u
ON p.id = u.prof_id
LEFT JOIN (
  SELECT id_prof,
     COUNT(id) opt_count
  FROM prof_opt
  GROUP BY id_prof
) o
ON p.id = o.prof_id

答案 2 :(得分:0)

试试这个

SELECT p.id, p.name, count(u.id_prof) AS 
nr_users, count(po.id_prof) AS nr_options
FROM profile p ,prof_opt po , user u    where p.id = u.id_prof and u.id = po.id_prof
GROUP BY p.id, u.id_prof