我在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


1.数据如下

从*中选择*;

1,'Ravi',2010
2,'Kumar',2011


从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


现在我写了一个查询结果集,如果b表具有a.id和a.year = b.year的记录,它应该返回a.id和count(b.id)。

例如-

id | cnt
------------
1  | 1
2  | 0
------------


这是我的查询-

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;


返回结果集-

id | cnt
------------
1  | 1


所以行为对我来说很明显,但是我不能像我之前所说的那样编写查询以获取结果集。

最佳答案

您的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;


这样,您将获得所有返回的a行。如果找不到匹配项,则cnt将为0

关于mysql - 无法编写正确的mysql连接查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33495351/

10-16 01:48
查看更多