如何计算所有行,并为结果集中不存在的行返回0

时间:2017-04-15 09:17:14

标签: mysql

我有这个MySQL架构Mysql Fiddle

GRPS                        GRP_USRS
grpID | name                usrID | grpID  
------------                --------------
1     | A                   1     | 1
2     | B                   2     | 1
3     | C                   3     | 1
4     | D                   4     | 1
5     | E                   16    | 2
                            11    | 3
                            12    | 3

我的目标是获取总用户数的所有组,包括0。 像这样:

grpID | count(*)
--------------
1     | 4
2     | 1
3     | 2
4     | 0
5     | 0

我试过了:

SELECT grps.grpID, IFNULL(COUNT(grp_usrs.usrID), 0) AS users
FROM grps 
     INNER JOIN grp_usrs ON grps.grpID = grp_usrs.grpID
GROUP BY grps.grpID ASC;

但结果是:

grpID | count(*)
--------------
1     | 4
2     | 1
3     | 2

如何包含计数为0的那些

2 个答案:

答案 0 :(得分:1)

只需使用left join

即可
SELECT grps.grpID, COUNT(grp_usrs.usrID) AS users
FROM grps 
LEFT JOIN grp_usrs ON grps.grpID = grp_usrs.grpID
GROUP BY grps.grpID ASC

您不需要查看ifnull。另请参阅this great explanation of joins

答案 1 :(得分:1)

你几乎做对了。你应该使用左连接:

if ($(current).attr("id") == "payment-page") {
                                $.ajax({
                                    url: 'https://openiban.com/validate/' + $("#iban").val(),
                                    success: function (data) {
                                        if (data.valid) {
                                            generatePDF(true);
                                            run();
                                        }

                                    },
                                    error: function(data) {
                                      // TODO: add better error for user
                                    },
                                    timeout: 3000
                                });
                            } else {
                                run();
                            }