简体   繁体   English

返回条件复杂的查询

[英]Return query with complex where condition

I have a table like this 我有这样的桌子

table allotment 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. 如您所见,我从日期2017-01-28选择到2017-01-31,并且表上有两个房间ID,在room_id 21中2017-01-29的is_closed日期是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 . 我想要的只是返回room_id 32,因为在room_id 21中,我选择的日期范围是is_closed中的值1。

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. 在where和子查询中,您已获取了allotment_id。 instead of this you must take room id 而不是这个,你必须带房间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 按房间分组,只接受零倍于is_closed标志的对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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