MySQL获得每个分支的查询总数

时间:2015-04-06 09:19:50

标签: php mysql

我有三张桌子,他们是以下

用户表

+---------+-----------+--------+
| user_id | user_name | branch |
+---------+-----------+--------+
| 1       | John      | 1      |
| 2       | Jim       | 2      |
| 3       | Jern      | 3      |
| 4       | Jack      | 1      |
| 5       | Jery      | 2      |
| 6       | Tom       | 3      |
| 7       | Sona      | 1      |
| 8       | Tina      | 3      |   
+---------+-----------+--------+

分支表

+-----------+----------------+
| branch_id | branch_name    |
+-----------+----------------+
| 1         | IT             |
| 2         | SALES          |
| 3         | Administration |
+-----------+----------------+

查询表

+------------+---------------+---------+
| enquiry_id | enquiry_name  | user_id |
+------------+---------------+---------+
| 1          | enqury_test1  | 1       |
| 2          | enqury_test2  | 2       |
| 3          | enqury_test3  | 1       |
| 4          | enqury_test4  | 3       |
| 5          | enqury_test5  | 2       |
| 6          | enqury_test6  | 5       |
| 7          | enqury_test7  | 1       |
| 8          | enqury_test8  | 2       |
| 9          | enqury_test9  | 4       |
| 10         | enqury_test10 | 6       |
| 11         | enqury_test11 | 2       |
| 12         | enqury_test12 | 7       |
+------------+---------------+---------+

从上面的表中可以清楚地看出,每个分支都包含许多用户。 这些用户发布多个查询。 我需要将每个分支的查询总数作为

branch id => number of enquiries

我尝试了各种查询。但我无法得到结果。任何人都可以帮忙吗? 我正在使用MySQL,我需要单个查询来执行此操作。

提前致谢

4 个答案:

答案 0 :(得分:1)

您需要countgroup by

select
b.branch_id,
count(e.user_id) as `total_enq`
from Branch b
left join User u on u.branch = b.branch_id
left join Enquiry e on e.user_id = u.user_id
group by b.branch_id

答案 1 :(得分:0)

为获得所需结果而必须执行的查询如下: -

$query = "SELECT u.branch, COUNT(u.user_id) AS `total_enquires` 
          FROM enquiry e INNER JOIN user u ON e.user_id = u.user_id
          GROUP BY u.branch"

这对您有帮助,我认为您不需要加入分支表,因为用户表已包含branch_id

答案 2 :(得分:0)

SELECT 
        bt.branch_id
        ,COUNT(enquiry_id) AS total_enquiry
FROM 
    enquiry_table et
    INNER JOIN user_table ut on ut.user_id = et.user_id
    INNER JOIN branch_table bt ON bt.branch_id = ut.branch
WHERE  
    1=1
GROUP BY
        bt.branch_id

你可以试试这个

答案 3 :(得分:0)

这是查询

SELECT `branch`,`branch_name`,count(`user`.`user_id`),count(`enquiry_id`) FROM `user` inner join `branch` on `user`.`branch`=`branch`.`branch_id` inner join `enquiry` on `user`.`user_id`=`enquiry`.`user_id` group by `branch` 

在这里试试 http://sqlfiddle.com/#!9/cf3eb/1