Mysql SQL项的剩余空间
我需要一些帮助 问:最好在1个查询中获取项目的总剩余空间Mysql SQL项的剩余空间,mysql,sql,Mysql,Sql,我需要一些帮助 问:最好在1个查询中获取项目的总剩余空间 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.G
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( * )
我想你需要这样的东西:
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)
将始终具有相同的MAXAllowerdItems值,COUNT(items.Group\u ID)
将是该组ID使用的行数
请参阅fiddle。不要忘记从查询中删除其中一个
,并删除select SUM(g.maxallowedeitems-count(*)之后的逗号,
…我想您仍然需要GROUP BY
子句,以便MAX
和/或count
聚合能够正常工作。。。否?@BroadCastic不客气:)如果您觉得答案有用,请不要忘记接受,如果您希望。。。谢谢