结合两个查询sql

时间:2018-04-09 08:46:00

标签: mysql sql

我不知道如何组合以下查询

QUERY 1

SELECT hotel.country, time.year, time.month, COUNT(booking.room_id) as booked 

FROM booking 
LEFT JOIN room on room.room_id = booking.room_id 

LEFT JOIN hotel on room.hotel_id = hotel.hotel_id 

LEFT JOIN time on booking.time_id = time.time_id 

GROUP BY hotel.country, time.year, time.month 

ORDER by hotel.country, time.year, time.month

QUERY 2

SELECT hotel.country, time.year, time.month, COUNT(checkout.room_id) as checkedout

FROM checkout

LEFT JOIN room on room.room_id = checkout.room_id

LEFT JOIN hotel on room.hotel_id = hotel.hotel_id

LEFT JOIN time on checkout.time_id = time.time_id

GROUP BY hotel.country, time.year, time.month

ORDER BY hotel.country, time.year, time.month

我希望输出如下

国家/地区,年份,月份,预订次数,结帐次数,总和(预订+结帐)

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

使用带聚合的mysql Union。

工会文档:https://dev.mysql.com/doc/refman/5.7/en/union.html 汇总文档:https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

以下联盟的例子:

SELECT 
    firstName, 
    lastName
FROM
    employees 
UNION 
SELECT 
    contactFirstName, 
    contactLastName
FROM
    customers;

希望这有帮助!

答案 1 :(得分:0)

set_vertex_attr

答案 2 :(得分:0)

解决此问题的一种方法是使用UNON ALL

SELECT h.country, t.year, t.month, SUM(is_booking) as booked, SUM(is_checkout) as checkedout
FROM ((SELECT b.room_id, b.time_id, 1 as is_booking 0 as is_checkout
       FROM booking b
      ) UNION ALL
      (SELECT c.room_id, c.time_id, 0 as is_booking, 1 as is_checkout
       FROM checkout c
      )
     ) bc  LEFT JOIN
     room r
     ON r.room_id = bc.room_id LEFT JOIN
     hotel h
     ON r.hotel_id = h.hotel_id LEFT JOIN
     time t
     ON bc.time_id = t.time_id 
GROUP BY h.country, t.year, t.month 
ORDER by h.country, t.year, t.month