在mysql中创建逻辑表达式以从表中提取数据
我有一个如下所示的数据集: 我的任务是根据签入和签出日期在MySQL中编写一个逻辑条件,以检索所有需要的住宿 包括3月23日晚上。我试过这个:在mysql中创建逻辑表达式以从表中提取数据,mysql,logic,Mysql,Logic,我有一个如下所示的数据集: 我的任务是根据签入和签出日期在MySQL中编写一个逻辑条件,以检索所有需要的住宿 包括3月23日晚上。我试过这个: check_in<="23/03/2019" and check_out>"23/03/2019" 签入“2019年3月23日” 但我发现,我还是留在了check-in='2019-03-21'和check-out= 未检索到“2019-03-25”,即使它包含23r。我想知道问题出在哪里,如何解决?谢谢:)使用一个子查询,该子查询按s
check_in<="23/03/2019" and check_out>"23/03/2019"
签入“2019年3月23日”
但我发现,我还是留在了check-in='2019-03-21'
和check-out=
未检索到“2019-03-25”
,即使它包含23r。我想知道问题出在哪里,如何解决?谢谢:)使用一个子查询,该子查询按stay\u id分组,并在HAVING
子句中检查您的要求:
select *
from tablename
where stay_id in (
select stay_id from tablename
group by stay_id
having '2019-03-23' between
max(case when event_type = 'check-in' then date end) and max(case when event_type = 'check-out' then date end)
)
或者由于退房日期(我假设)晚于或等于退房日期:
select *
from tablename
where stay_id in (
select stay_id from tablename
group by stay_id
having '2019-03-23' between min(date) and max(date)
)
或者,如果您想为每个保留一行id
:
select stay_id, min(date) check_in_date, max(date) check_out_date
from tablename
group by stay_id
having '2019-03-23' between min(date) and max(date)
您需要将它与自身连接起来,以便能够在这两个术语上进行搜索。假设您的表被称为
停留在:
选择a.stay\u id、a.date check\u in、b.date check\u FROM stays a加入a.stay\u id=b.stay\u id和a.event\u type='check-in'和b.event\u type='check-out',其中a.date“2019-03-23”代码>假设每个人都已签出:
select stay_id
from tbl
where event_type = 'check-in' and date <= '2019-03-23'
and stay_id in
(select stay_id
from tbl
where event_type = 'check-out' and date > '2019-03-23')
选择停留\u id
来自tbl
其中事件类型=‘登记’和日期‘2019-03-23’)
我可以稍后编辑以创建一个逻辑来包含尚未签出的人您尝试的完整查询是什么?