Android SQLite:连接两个包含计数表达式的select语句
我有一个包含文件夹列表的表,每个文件夹都有一个ID和描述Android SQLite:连接两个包含计数表达式的select语句,android,sqlite,Android,Sqlite,我有一个包含文件夹列表的表,每个文件夹都有一个ID和描述 SELECT * FROM folders _id | description --------------------------- 1 | default 2 | test 我有一个包含图像列表的图像表,每个图像都有一个folderid select folderid, count(*) as imagecount from images GROUP BY folderid; folderid| imag
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列。有什么想法吗?你很接近
SELECT _id, description, imagecount
from folders,
(select folderid, count(*) as imagecount from images GROUP BY folderid)
WHERE _id = folderid;
你很接近
SELECT _id, description, imagecount
from folders,
(select folderid, count(*) as imagecount from images GROUP BY folderid)
WHERE _id = folderid;
这也是一个有效的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
或者不使用sum()和case语句,只需将
count(i.folderid)作为imagecount执行即可,这也是一个有效的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)作为imagecount
更改f.description by id(可能重复)是的,如果可以重复,最好按f.id分组,f.description
更改f.description by id(可能重复)是的,如果可以重复,最好按f.id分组,f.说明