我有一个名为列表的日期列表,人们可以注册参与预订。
listings
id | date | capacity
1 2010-01-01 3
2 2010-01-02 1
3 2010-02-02 2
bookings
id | listing_id | name
1 1 Chris
2 1 Steve
3 1 Allen
4 2 Tracy
我想要做的是查询,该查询仅根据预订返回打开的列表。
查询只返回id = 3的列表。因为它没有预订且容量为2。
Sample query which won't work:
SELECT
*
FROM
listings
HAVING COUNT(
SELECT * FROM bookings WHERE listings.id=bookings.listing_id
) < capacity
感谢任何帮助。
答案 0 :(得分:2)
SELECT *
FROM listings
WHERE capacity > (SELECT count(*)
FROM bookings
WHERE listings.id=bookings.listing_id)
答案 1 :(得分:1)
SELECT
listings.id,
max(listings.date),
max(listings.capacity)
FROM listings
left join bookings on listings.id = bookings.listing_id
group by listings.id
having COUNT(bookings.listing_id) < max(listings.capacity)
答案 2 :(得分:0)
*我自己,我会加入然后算一下:
SELECT COUNT(*) as count
FROM listings, bookings
WHERE listings.id=bookings.listing_id
AND count < listings.capacity
GROUP by listings.id
我没有测试过,但这是一般的想法!