无法在mysql中使用group by获得正确的结果

时间:2014-10-21 10:14:58

标签: mysql group-by

我有2个SQL表

CREATE TABLE A(
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  name CHAR(1) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE B(
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  A_id INT(10) UNSIGNED NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO A VALUES (1, 'A'), (2, 'B'), (3, 'C'), (4, 'A');
INSERT INTO B VALUES (1, 1), (2, 2), (3, 4), (4, 4);

表格看起来像这样:

select * from A;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
|  4 | A    |
+----+------+

select * from B;
+----+------+
| id | A_id |
+----+------+
|  1 |    1 |
|  2 |    2 |
|  3 |    4 |
|  4 |    4 |
+----+------+

现在我想知道表B中表A中的每个元素有多少。使用我希望看到的其他词:

A = 3
B = 1
C = 0

我尝试用SELECT name, count(*) FROM A, B WHERE A.id = A_id GROUP BY A.id;执行此操作,但它返回的内容非常奇怪。有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

您应该使用LEFT JOIN,而不是GROUP BY A.id,而应使用name

SELECT A.name, COUNT(B.A_id)
FROM A
LEFT JOIN B ON A.id = B.A_id
GROUP BY A.name;

答案 1 :(得分:1)

你只需要一个左外连接来处理B中没有A的条件:

SELECT A.Name, COUNT(b.id)
FROM A
LEFT OUTER JOIN B on A.id = B.a_id
GROUP BY A.Name;

SqlFiddle here

答案 2 :(得分:1)

查询

SELECT a.name,COUNT(b.A_id) as `count`
FROM A a
LEFT JOIN B b
ON a.id=b.A_id
GROUP BY a.name;

Fiddle Demo