简体   繁体   中英

Return query with complex where condition

I have a table like this

table allotment

allotment_id | date | room_id | is_closed
-----------------------------------------
1 | 2017-01-28 | 21 | 0
2 | 2017-01-29 | 21 | 1
3 | 2017-01-30 | 21 | 0
4 | 2017-01-31 | 21 | 0
5 | 2017-01-28 | 32 | 0
6 | 2017-01-29 | 32 | 0
7 | 2017-01-30 | 32 | 0
8 | 2017-01-31 | 32 | 0

I was try query like this :

SELECT *
FROM allotment
WHERE date BETWEEN '2017-01-28' AND DATE_SUB('2017-01-31', INTERVAL 1 DAY)
AND is_closed = 0
AND date >= '2017-01-28' AND l.`date` <= DATE_SUB('2017-01-31', INTERVAL 1 DAY) AND allotment_id NOT IN (select allotment_id FROM allotment WHERE is_closed = 1 AND date >= '2017-01-28' AND date <= '2017-01-31')

As you can see I select from date 2017-01-28 until 2017-01-31 and there is two room id on table which in room_id 21 date 2017-01-29 is_closed is 1.

What I want is return just room_id 32 because in room_id 21 where date range I selected it was value 1 in is_closed .

I have tried my query but it doesn't working. How could I to do that.

Thank you.

in where and subquery you have taken allotment_id. instead of this you must take room id

SELECT *
FROM allotment
WHERE date BETWEEN '2017-01-28' AND DATE_SUB('2017-01-31', INTERVAL 1 DAY)
AND is_closed = 0 and room_id not in (select room_id FROM allotment WHERE is_closed = 1 AND date >= '2017-01-28' AND date <= '2017-01-31')

Group by the room and take only those having zero times the is_closed flag

SELECT room_id
FROM allotment
WHERE date >= '2017-01-28' 
  AND date <= '2017-01-31'
group by room_id
having sum(is_closed = 1) = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM