[英]SQLite: Joining two select statements that include a count expression
我有一個包含文件夾列表的表,每個文件夾都有一個ID和說明
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列。 有任何想法嗎?
這也是一個有效的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
你近了...
SELECT _id, description, imagecount
from folders,
(select folderid, count(*) as imagecount from images GROUP BY folderid)
WHERE _id = folderid;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.