Combining two queries in mySQL

空扰寡人 提交于 2019-12-24 23:31:48

问题


I'm trying to combine the results of two queries. I'm not very proficient in mysql so I'm here for some help.

The first query is as follows:

select count(roomtypeid) as bookedrooms, day 
from event_guest_hotel 
where hotelid = 1 and roomtypeid = 1 
 group by day;

This returns:

The second query:

SELECT ehr.reservationid, ehr.day, h.name AS hotelname, 
ehr.totalrooms as requested_rooms, r.name AS roomname
            FROM event_hotel_reservation ehr 
            INNER JOIN hotel_room_type r 
            ON ehr.roomtypeid = r.roomtypeid 
            INNER JOIN hotel h
            ON ehr.hotelid = h.hotelid  
            WHERE totalRooms != 0 
            AND reservationID = '1'

This returns:

Can I combine the first query with the second one, so I get the results of the first one in another resultcolumn next to 'roomname'? That way I know how many rooms are already booked and how many were originally requested from one single query.


回答1:


Try:

SELECT ehr.reservationid, ehr.day, h.name AS hotelname, 
    ehr.totalrooms as requested_rooms, r.name AS roomname, 
    egh.bookedrooms
FROM event_hotel_reservation ehr 
INNER JOIN hotel_room_type r ON ehr.roomtypeid = r.roomtypeid 
INNER JOIN hotel h ON ehr.hotelid = h.hotelid    
left outer join (
    select hotelid, count(roomtypeid) as bookedrooms, day 
    from event_guest_hotel 
    where roomtypeid = 1 
    group by hotelid, day
) egh on h.hotelid = egh.hotelid and ehr.day = egh.day
WHERE totalRooms != 0 
    AND reservationID = '1'


来源:https://stackoverflow.com/questions/7272260/combining-two-queries-in-mysql

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