2015-09-11 48 views
0

我有一个数据库MySQL的免费获得点查询

帐篷(ID,numberOfSpots)

人(ID,姓名,tentId)

帐篷

以下结构
+----+---------------+ 
| id | numberOfSpots | 
+----+---------------+ 
| 1 |    5 | 
| 2 |    3 | 
| |    | 
+----+---------------+ 

+----+----------+--------+ 
| id | name | tentId | 
+----+----------+--------+ 
| 1 | Simon |  1 | 
| 2 | Jasmin |  1 | 
| 3 | Markus |  1 | 
| 4 | Romy  |  1 | 
| 5 | Fabrizia |  1 | 
| |   |  | 
+----+----------+--------+ 

查询

我想查询时,得到它有一个可用的自由现货下一tentId。 因此,对于上面的示例数据,它将是tentId = 2。如果将少了一个人,那将是我来tentId = 1

了这样的事情:

select t.Id 
from Tent as t 
left join (
    select p.tentId, count(*) as occupiedSpots 
    from person as p 
    group by p.tentId) as i ON i.tentId = t.id 
where z.numberOfSpots > i.occupiedSpots 

,但我没有得到结果......

什么时我做错了?

在此先感谢

+0

真的,你想要第一个tentid,不是在Person中存在,而是在Tent中? – splash58

+0

我想要的第一个tentid与* numberOfSpots的关系比人少* – xeraphim

+1

@xeraphim谁是z作为别名? – Cosmin

回答

1

你应该occupiedSpots

select t.Id 
from Tent as t 
left join (
    select p.tentId, count(*) as occupiedSpots 
    from person as p 
    group by p.tentId) as i ON i.tentId = z.id 
where t.numberOfSpots > IFNULL(i.occupiedSpots,0) 
+0

哦,这工作就像一个魅力,谢谢:) – xeraphim

+0

酷,你可以验证我的回答则;-) –

+0

灿你首先纠正它关于z。 – jarlh

1

避免子查询测试是否为空值,你应该能够做这样的事情: -

SELECT tent.id, tent.numberOfSpots - COUNT(person.id) AS free_places 
FROM tent 
LEFT OUTER JOIN person 
ON tend.id = person.tendId 
GROUP BY tent.id 
HAVING free_places > 0 

获取每个帐篷的人数并从帐篷容量中减去。并使用一个HAVING子句来返回那些具有多于零空格的元素