SQL从2张表计算总数

时间:2018-09-28 03:05:47

标签: php jquery mysql laravel count

我有2个表Bank and Applicant,如何查询显示所有银行并计算使用该银行的申请人数量

[银行] [1]

| id | Bank_desc    
|----|---------
| 1  | Ambank  
| 2  | Maybank  
| 3  | RHB BANK 
| 4  | OSBC     

[申请人] [2]

| id | Name | Bank|
|----|------|----|
|  1 | JACK |  3 |
|  2 | ANDY |  1 |
|  3 | VOID |  1 |

我想展示这样的东西, [结果] [2]

| id | Bank     |Total|
|----|----------|----|
|  1 | Ambank   |  2 |
| 2  | Maybank  |  0 |
| 3  | RHB BANK |  1 |
| 4  | OSBC     |  0 |

我尝试过此sql

SELECT b.Bank_desc, Count(a.id),
FROM applicant a
LEFT JOIN bank b on b.id= a.bank
GROUP BY b.bank

但结果仅显示具有价值的银行

[结果] [2]

| id | Bank     |Total|
|----|----------|----|
|  1 | Ambank   |  2 |
| 2  | RHB BANK |  1 |

任何帮助将不胜感激,在此先感谢!

2 个答案:

答案 0 :(得分:1)

如果您反转表的顺序,您当前的查询将起作用:

SELECT
    b.id,
    b.Bank,
    COUNT(a.Bank) AS Total
FROM Bank b
LEFT JOIN Applicant a
    ON b.id = a.Bank
GROUP BY
    b.id,
    b.Bank;

enter image description here

Demo

答案 1 :(得分:0)

选择银行名称COUNT,来自银行b的COUNT(u.bank_id)通过u.bank_id由b.id = u.bank_id GROUP加入用户u