我在mysql中有以下2个表
1. Table-Name a
id int auto-increment PK
name varchar not null
year int(4) not null
2. Table-Name b
id int auto-increment PK
term varchar not null
a_id int FK references a.id
year int(4) not null
Run Code Online (Sandbox Code Playgroud)
1.数据如下
选择*来自a;
1,'Ravi',2010
2,'Kumar',2011
Run Code Online (Sandbox Code Playgroud)
select*from b;
1,'a',1,2009
2,'b',1,2010
3,'c',1,2008
4,'d',2,2008
5,'e',2,2009
6,'f',2,2010
Run Code Online (Sandbox Code Playgroud)
现在我写了一个结果集的查询,它应该返回a.id并计算(b.id)如果b表有a.id和a.year = b.year的记录
例如 -
id | cnt
------------
1 | 1
2 | 0
------------
Run Code Online (Sandbox Code Playgroud)
这是我的查询 -
select a.id,count(b.id) cnt from a
left join b
on b.a_id=a.id
where a.year=b.year
group by id;
Run Code Online (Sandbox Code Playgroud)
返回结果集 -
id | cnt
------------
1 | 1
Run Code Online (Sandbox Code Playgroud)
所以行为对我来说非常明显,但我无法编写查询来获取结果集,正如我之前所说的那样.
你的WHERE条款基本上转换LEFT JOIN为INNER JOIN.您应该将谓词移动WHERE到ON:
select a.id,count(b.id) cnt from a
left join b
on b.a_id=a.id AND a.year=b.year
group by id;
Run Code Online (Sandbox Code Playgroud)
这样您就可以获得所有 a返回的行.如果找不到匹配,那么cnt将是0.
| 归档时间: |
|
| 查看次数: |
26 次 |
| 最近记录: |