2013-04-28 103 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