2011-07-28 55 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;