SQLite:连接两个包含计数表达式的select语句

时间:2011-07-28 18:43:55

标签: android sqlite

我有一个包含文件夹列表的表,每个文件夹都有一个ID和描述

SELECT * FROM folders

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

我有一个包含图像列表的图像表,每个图像都有一个文件夹

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 个答案:

答案 0 :(得分: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语句代替sum(),你可以count(i.folderid) as imagecount

答案 1 :(得分:1)

你很亲密......

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