我有以下MySQL查询:
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-02' AND startdate <= '2015-05-09'
UNION ALL
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-11' AND startdate <= '2015-05-12'
是否可以合并这两个查询,而不是使用UNION ALL
?
答案 0 :(得分:2)
您可以使用OR
运算符代替
SELECT *
FROM bookings
WHERE record_id = 7
AND status = 'available'
AND ((startdate >= '2015-05-11' AND startdate <= '2015-05-12') or (startdate >= '2015-05-02' AND startdate <= '2015-05-09'))
答案 1 :(得分:2)
这个工作:
SELECT *
FROM bookings
WHERE record_id = 7 AND status = 'available' AND
((startdate >= '2015-05-02' AND startdate <= '2015-05-09') or (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
答案 2 :(得分:2)
您可以使用OR
运算符来获取两个日期范围:
SELECT *
FROM bookings
WHERE record_id = 7 AND
status = 'available' AND
((startdate >= '2015-05-02' AND startdate <= '2015-05-09') OR
(startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
答案 3 :(得分:1)
离开这部分:
SELECT * FROM bookings WHERE record_id = 7 AND status = 'available'
添加:
AND ((startdate >= '2015-05-02' AND startdate <= '2015-05-09') OR (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
如果第一个和条件得到真,或者第二个和条件
,则OR条件将返回true对于您正在使用的那些和条件,您可能需要查看sql BETWEEN语句:http://www.w3schools.com/sql/sql_between.asp
您可以在第一部分之后执行此操作:
AND startDate >= '2015-05-02' AND startDate <= '2015-05-12' AND NOT startDate = '2015-05-10'
当你正在使用硬编码日期时,你不需要的唯一一个是5月10日