MYSQL: Vacant / occupied rooms as now

↘锁芯ラ 提交于 2020-01-15 13:39:06

问题


I have three tables room_charges, room_category and patient_detail

room_category
id room_category
1      twin
2      classic
3      Deluxe

room_charges
id room_name room_category
1    tw1        1
2    tw2        1
3    cl1        2
4    cl2        2
5    dl1        3

patient_detail

id patient_name room_name room_category admission_date_time discharge_date_time discharged
1   Mr x             1        1          10-12-14 10:40        12-12-14 08:40      1
2   Mr y             1        1          12-12-14 11:40        15-12-14 13:10      1
3   mr z             1        1          15-12-14 14:40             null          null

I am using the query to find the vacant_beds detail, but as per the patient_detail table room_id 1 is occupied, but I am getting it vacant. The query I am using is like this:

select `rc`.`id` AS `id`,
        `rct`.`room_category` AS `room_category`,
        group_concat(`rc`.`room_name` separator ',') AS `vacant_beds` 
from ((`room_charges` `rc` 
       left join `patient_detail` `pd` on((`rc`.`id` = `pd`.`room_name`))) 
      join `room_category` `rct` on((`rc`.`room_category` = `rct`.`id`))) 
where ((`pd`.`discharged` = 1)  or    isnull(`pd`.`admission_date_time`))  
group by `rc`.`room_category` 
having max(admission_date_time)

I am creating a view to get the vacant bed information and cannot use sub-query. Thanks a lot for a suitable solution on this.

Ok I am putting below my desired result as below:

room_category room_name
twin            tw2
classic         cl1,cl2
deluxe          dl1

This means that as per the patient detail table room tw1 is still occupied and should not show in the query result.


回答1:


Your question is quite hard to follow because the columns in your query do not match the columns in the sample data. Also, you have no desired results.

I think you need to move the date comparisons into an on clause and then look for non-matches in the where:

select rct.room_category AS room_category,
       group_concat(rc.room_name separator ',') AS vacant_beds
from room_charges rc join
     room_category rct
     on rc.room_category = rct.id left join
     patient_detail pd
     on rc.id = pd.room_name and
        (pd. discharge_date_time is null or
         curdate() between admission_date_time and discharge_date_time)
where pd.id is null
group by rc.room_category ;


来源:https://stackoverflow.com/questions/27686182/mysql-vacant-occupied-rooms-as-now

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!