我有这两个表。统计两个表中的相关字段
富
+----+--------+
| id | letter |
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
+----+--------+
酒吧
+----+------+--------+--------+
| id | name | foo_id | status |
| 1 | fox | 1 | 1 |
| 2 | cat | 1 | 0 |
| 3 | dog | 3 | 1 |
| 4 | bird | 5 | 1 |
| 5 | cow | 5 | 0 |
+----+------+--------+--------+
现在,我要算信的出现仅仅与状态栏表等于1
所以LEFT JOIN
状态
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
这是我想要的结果。
+--------+-------+
| letter | count |
| A | 1 |
| B | 0 |
| C | 1 |
| D | 0 |
| E | 1 |
+--------+-------+
我到目前为止试过的东西。
SELECT letter, count(foo_id) AS count
FROM foo f LEFT JOIN bar b on f.id = b.foo_id
GROUP BY letter
我知道我的查询是错误的,因为它不符合1.过滤状态但是,当我尝试添加WHERE status = 1
到我的查询。似乎。
什么应该是查询以实现我想要的结果?
如果你用'status = 1'过滤你的输出将是'A 1,C 1,E 1'。你如何让A有count = 2? –