2016-12-16 45 views
0

我有两个表像这样:加入表的SQL不是无效

create table classe (
id integer primary key, 
name varchar not null 
); 

create table alunno (
id integer primary key, 
id_classe integer not null 
); 

我会采取一种独特的查询以下数据:

  • classe.id
  • classe.name
  • alunno有一个特定的计数id_classe

这样我就可以做这样的事情:

select a.id, a.name, count(b.id) 
from classe a, alunno b 
where a.id = :1 and b.id_classe = a.id; 

但如果计数= 0我在resultset..so空值我向始终节记录的信息,如果没有一个alunno记录存在该节我会计数= 0,不会使整个输出失效。如何获得这个结果集?

我也试图与左加入,但可能是错误的结构性..

我补充一点,我使用的SQLite所以一些SQL命令不能在它被用来

非常感谢你的帮助。

回答

0

您需要将连接条件放在LEFT JOINON子句中。

SELECT a.id, a.name, IFNULL(COUNT(b.id), 0) 
FROM classe AS a 
LEFT JOIN alunno AS b ON b.id_classe = a.id 
WHERE a.id = :1 
0

count(x)数只非NULL x值,但count(*)计数的所有行:

SELECT a.id, 
     a.name, 
     count(*) 
FROM classe AS a 
LEFT JOIN alunno AS b ON b.id_classe = a.id 
WHERE a.id = :1 
GROUP BY a.id; 

(您仍需要一个外部联接,以获得classe行不匹配的分组是必要仅当。您可能会搜索多个ID。)

或者,使用correlated subquery查找计数:

SELECT id, 
     name, 
     (SELECT count(*) 
     FROM alunno 
     WHERE id_classe = classe.id 
     ) AS count 
FROM classe 
WHERE id = :1;