简体   繁体   English

计算两个表中的相关字段

[英]counting related fields in two tables

I have these two tables. 我有这两张桌子。

foo FOO

+----+--------+
| id | letter | 
| 1  | A      | 
| 2  | B      | 
| 3  | C      |
| 4  | D      |
+----+--------+

bar 酒吧

+----+------+--------+--------+
| 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      |
+----+------+--------+--------+

Now, I want to count the occurrences of the letter in the bar table with only status equals 1 现在,我想计算只有状态等于1的条形表中字母的出现情况

So LEFT JOIN states 所以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.

This is the result I want. 这是我想要的结果。

+--------+-------+
| letter | count |
| A      | 1     |
| B      | 0     |
| C      | 1     |
| D      | 0     |
| E      | 1     |
+--------+-------+

What I have tried so far. 到目前为止我尝试过的。

SELECT letter, count(foo_id) AS count
FROM foo f LEFT JOIN bar b on f.id = b.foo_id
GROUP BY letter

I know my query is wrong because it does not filter the status with 1. But when I try to add WHERE status = 1 to my query. 我知道我的查询是错误的,因为它不使用1过滤状态。但是当我尝试向查询中添加WHERE status = 1 Seems off. 似乎关闭。

What should be the query to achieve my desired result? 要达到我想要的结果应该是什么查询?

You need to add your filter to the join predicate: 您需要将过滤器添加到联接谓词:

SELECT letter, count(foo_id) AS count
FROM   foo f 
       LEFT JOIN bar b 
         ON f.id = b.foo_id 
         AND b.status = 1
GROUP BY letter;

Putting it in the where clause will effectively turn your left join into an inner join, because where there is no match in bar , you will end up with WHERE NULL = 1 , which is not true, so this record from foo will not be returned. 将其放在where子句中将有效地将您的左联接变为内部联接,因为在bar没有匹配的地方,您将最终得到WHERE NULL = 1 ,这是不正确的,因此不会返回来自foo该记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM