使用LEFT JOIN和GROUP BY的COUNT(*)在MySQL

时间:2016-12-01 19:13:20

标签: mysql join group-by

我试图从包含外表中外观计数的表中获取结果。此表可以有0个或更多个外观。

如下例所示:

表:颜色

+------+---------+
|  id  |   name  |
+------+---------+
|  1   |   red   |
|  2   |   blue  |
|  3   |  yellow |
|  4   |  green  |
+------+---------+
表:水果

+--------+----------+
|  name  | color_id |
+--------+----------+
| apple  |    1     |
| banana |    3     |
| grape  |    4     |
| lemon  |    3     |
+--------+----------+

所以我需要列出水果表中的每种颜色和事件,返回如下内容:

1, red, 1
2, blue, 0
3, yellow, 2
4, green, 1

我正在尝试使用此查询:

SELECT `c`.`id`, `c`.`name`, COUNT(1)
FROM color `c`
LEFT JOIN fruit `f`
ON `c`.`id` = `f`.`color_id`
GROUP BY `c`.`id`

此查询为"蓝色"返回 1 的计数。而不是 0 。因为颜色"蓝色"没有出现在水果表中

2 个答案:

答案 0 :(得分:7)

这有效:

SELECT c.id, COUNT(f.name)
FROM color c
LEFT JOIN fruit f ON c.id = f.color_id
GROUP BY c.id

你必须计算一个水果字段,以便可以返回NULL,它变为零。

答案 1 :(得分:2)

你把count(1),改变计数(f.color_id)

$(document).ready(function() {


 console.log("ready");
  $('#registerUserButton').prop("disabled", true);

  $('#reg_passwordConfirm').bind('keyup', function() {
    var Password = $("#reg_password").val(); // you have to add the .val()
    var confirmPassword = $("#reg_passwordConfirm").val(); // you have to add the .val()

if ((Password == confirmPassword) && (Password > 1) && (confirmPassword === 1)) {
  $('#registerUserButton').prop("disabled", false);
}else { //error handling for the password 
var errMsg = "Sorry but the passwords doesnt match.";
$('#registerUserButton').append(errMsg);
$('#registerUserButton').prop("disabled", true); //Making sure button is disabled
}

});
});