2011-07-28 37 views
0

我有一个包含的文件夹的列表的表,每个文件夹有一个ID和说明SQLite的:连接两个选择语句,其中包括一个计数表达

SELECT * FROM folders 

_id | description 
--------------------------- 
1 | default 
2 | test 

我有一个包含图像的列表的图像表,每个图像具有folderid

select folderid, count(*) as imagecount from images GROUP BY folderid; 

folderid| imagecount 
--------------------------- 
1  | 4 
2  | 5 

我希望能够编写一个查询返回的所有文件夹列表,用它的描述,以及多少图像是里面

????? 

_id | description | imagecount 
------------------------------------------------------ 
1 | default  | 4 
2 | test  | 5 

我尝试以下查询:

SELECT _id, description from folders, (select folderid, count(*) as imagecount from images GROUP BY folder) WHERE _id = folderid; 

但是它不工作,因为它不返回imagecount列。有任何想法吗?

回答

2

这也是一个有效的SQLite的查询,将答案回到你的问题:有多少影像每个文件夹中?

 select f.description, sum (case when i.folderid is null then 0 else 1 end) as imagecount 
     from folders f left join images i on i.folderid = f.id 
     group by f.description 

或代替之和()的一个case语句,你可以只是做count(i.folderid) as imagecount

+0

变化f.description通过ID(也许是重复) –

+0

是的,如果它可以重复,最好做'组由f.id,f.description' – Tim

1

你靠近...

SELECT _id, description, imagecount 
from folders, 
(select folderid, count(*) as imagecount from images GROUP BY folderid) 
WHERE _id = folderid;