我有两张桌子 - >公寓和可用性。
在公寓中,有关于公寓的所有信息。在表格可用性中,有关于未来365天公寓可用性的所有信息。
表公寓:
id, name
实施例:
1, Apartment 1
2, Apartment 2
表格可用性:
id, apartment_id, date, status
实施例:
1, 1, 2017-06-01, free
2, 1, 2017-06-02, booked
3, 1, 2017-06-03, free
4, 1, 2017-06-04, free
5, 1, 2017-06-05, free
...
6, 2, 2017-06-05, free
7, 2, 2017-06-05, free
8, 2, 2017-06-05, free
9, 2, 2017-06-05, booked
10, 2, 2017-06-05, free
...
现在我希望在多个日期范围内搜索免费公寓一周,如:
SELECT apartments where id in (
SELECT apartment_id
FROM availabilities
WHERE EXISTS (
SELECT apartment_id
FROM availabilities as a
WHERE availabilities.apartment_id = a.apartment_id
AND date >= "2017-06-01"
AND date < "2017-06-08"
AND status = "free"
GROUP BY apartment_id
HAVING COUNT(apartment_id) = DATEDIFF("2017-06-08", "2017-06-01"))
OR EXISTS (
SELECT apartment_id
FROM availabilities as a
WHERE availabilities.apartment_id = a.apartment_id
AND date >= "2017-06-02"
AND date < "2017-06-09"
AND status = "free"
GROUP BY apartment_id HAVING COUNT(apartment_id) = DATEDIFF("2017-06-09", "2017-06-02"))`
这应该查找日期范围内一周的所有可能性(2017-06-01 - 2017-06-30)
我的问题是,我们有很多公寓,这个查询的加载时间非常长。
任何有关更好解决方案的想法?
答案 0 :(得分:0)
使用(COUNT(*)和过滤器修复状态=&#34;预订&#34;)= 0
查询速度提高了30%。