用LEFT JOIN计数仅显示一行

时间:2018-12-26 22:57:31

标签: mysql

我的数据库中有以下数据:

scu_banks:

---------------------------------
|   id    |   type   |   name   |
|-------------------------------|  
|    1    |    1     |   One    |
|    2    |    1     |   Two    |
|    3    |    2     |  Three   |
|    4    |    3     |   Four   |
---------------------------------

scu_statement:

---------------------------------
|   id    |   code   |    status    |
|-----------------------------------|  
|    1    |    1     |      0       |
|    2    |    1     |      1       |
|    3    |    2     |      0       |
|    4    |    1     |      0       |
-------------------------------------

我想做的是我要选择表scu_banks中的所有行,并计算状态为0的行数。数据应表示为:

--------------------------------------------------------------
| scu_banks.type | scu_banks.name |   status  | scu_banks.id |
--------------------------------------------------------------
|       1        |      One       |     2     |      1       |
|       1        |      Two       |     0     |      2       | //There is no row with status 0
|       2        |     Three      |     0     |      3       |
|       3        |      Four      |     0     |      4       |
--------------------------------------------------------------

当我运行sql语句时,我得到以下数据:

---------------------------------------------------------------
| scu_banks.type | scu_banks.name |    status   | scu_banks.id |
--------------------------------------------------------------
|       1        |      One       |      2      |      1       |
---------------------------------------------------------------

在这种情况下,我得到的数据是正确的。 2它是表scu_statement中所有行的总数。该语句也不会显示数据库中的其他行。

有人知道我的sql语句出了什么问题吗?

这是我的sql语句:

SELECT b.type 'scu_banks.type',
b.name 'scu_banks.name',
count(y.status) 'status',
b.id 'scu_banks.id'
FROM scu_banks b
LEFT JOIN (SELECT s.code, count(s.status) status
           FROM scu_bankstatement s 
           WHERE status='0'
           GROUP BY s.code) y
           ON y.code = b.id

1 个答案:

答案 0 :(得分:1)

您的外部查询中需要一个GROUP BY,否则查询将只计算所有存储区的状态。您也可以只LEFT JOIN编写代码/ id和status = 0的两个表来简化查询

SELECT b.type `scu_banks.type`,
b.name `scu_banks.name`,
COUNT(s.status) `status`,
b.id `scu_banks.id`
FROM scu_banks b
LEFT JOIN scu_statement s ON s.code = b.id AND s.status = 0
GROUP BY b.id, b.name, b.type

输出

scu_banks.type  scu_banks.name  status  scu_banks.id
1               One             2       1
1               Two             1       2
2               Three           0       3
3               Four            0       4

Demo on dbfiddle