2013-04-28 43 views
0

我需要一些幫助 問:獲得項目總剩餘空間最好在1個查詢剩餘的空間留給項目SQL

Grops, items 
Group can contain only MaxAllowed items 

Groups table 
(ID, MAXAllowerdItems) 

Items 
(ID, Group_ID, Name) 

這是不正確的查詢,但起點

select SUM(g.MaxAllowedItems - count(*)), 
from FROM items i, Groups g 
where g.ID=i.Group_ID 
GROUP BY i.Group_ID 
HAVING g.MaxAllowedItems > count(*) 
+0

不要忘記從查詢中刪除一個'FROM'並刪除'select SUM(g.MaxAllowedItems - count(*))後的逗號,'... – jerdiggity 2013-04-28 20:06:22

回答

1

我認爲你需要這樣的事情:

SELECT 
    groups.ID, 
    MAX(MAXAllowerdItems) - COUNT(items.Group_ID) as remaining_spaces 
FROM 
    groups LEFT JOIN items 
    ON groups.ID = items.Group_ID 
GROUP BY 
    groups.ID 
HAVING 
    remaining_spaces > 0 

MAX(MAXAllowerdItems) will always ha具有相同的MAXAllowerdItems值,並且COUNT(items.Group_ID)將是該組ID的已用行數。

請參閱小提琴here

+1

我想你還是會希望在那裏有'GROUP BY'子句,以便'MAX'和/或'COUNT'聚合起作用......不是嗎? – jerdiggity 2013-04-28 20:13:40

+0

@jerdiggity是的......當然......我更新了,謝謝! – fthiella 2013-04-28 20:14:52

+0

很棒!謝謝 – 2013-04-29 10:11:00