2013-02-14 48 views
0

我繼承了舊的SQLite數據庫,我不應該改變(這是一個要求)。有很多的表,但我會集中在兩個:增強當前的SQLite查詢

songs 
---------- 
song_id (primary autoincrement) 
group_id (external) 
title 
audio_file_path 
wasPurchased (boolean, 0/1) 

groups 
---------- 
group_id (primary autoincrement, related to songs group_id) 
group_name 

目前,該應用程序需要執行這個查詢:

SELECT song_id,title,audio_file_path,wasPurchased,G.group_name AS groupName, 
G.group_id AS groupId FROM songs AS S JOIN groups AS G ON S.group_id=G.group_id 
ORDER BY groupName DESC 

有什麼辦法,用相同的查詢,提取有多少不同的G.group_id已被購買= 0?

任何幫助表示讚賞。

回答

0
SELECT song_id,title,audio_file_path,wasPurchased, 
G.group_name AS groupName, G.group_id AS groupId, 
SUM (SELECT DISTINCT g.group_id 
     FROM yourtables/JOIN 
     WHERE wasPurchased = 0) as nb 
FROM songs AS S 
JOIN groups AS G ON S.group_id=G.group_id 
ORDER BY groupName DESC 

不知道這是最好的方式(從來沒有試過一個選擇的總和,但...),但我認爲這會幫助你。

+0

我發現了一個不同的解決方案,有一個子查詢(就像你的),沒有JOIN和SUM:'SELECT COUNT(DISTINCT(group_id))FROM FROM WHERE購買= 0)AS nb'。你的解決方案做了一個稍微不同的事情,所以也許我解釋不好我的需求。 – ContentiousMaximus 2013-02-14 13:18:27