MySQL加入两个单独的查询结果

时间:2013-12-10 05:35:40

标签: mysql

我有两个不同的查询,例如

// This query will return past month records
SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS 'bookingdate', COUNT(*) AS bookings
FROM booking b JOIN restaurants r ON r.list_id = b.list_id
WHERE b.bookingdate BETWEEN 1383224400 AND 1385730000 GROUP BY b.list_id

// This query will return current month records
SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS 'bookingdate', COUNT(*) AS bookings
FROM booking b JOIN restaurants r ON r.list_id = b.list_id
WHERE b.bookingdate BETWEEN 1385816400 AND 1388408400 GROUP BY b.list_id

两个查询的结果字段 list_id,name,city,bookingdate,bookings

我想将两个查询结果合并为一个,并希望结果字段如 list_id,name,city,bookingdate,bookings_lastmonth,bookings_currentmonth

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:3)

使用UNION属性: -

SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS 'bookingpreviousdate', '0' AS bookingnextdate, COUNT(*) AS bookings
FROM booking b JOIN restaurants r ON r.list_id = b.list_id
WHERE b.bookingdate BETWEEN 1383224400 AND 1385730000 GROUP BY b.list_id
UNION
SELECT b.list_id, r.name, r.city, '0' AS 'bookingpreviousdate', 'FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s')' AS bookingnextdate, COUNT(*) AS bookings
FROM booking b JOIN restaurants r ON r.list_id = b.list_id
WHERE b.bookingdate BETWEEN 1385816400 AND 1388408400 GROUP BY b.list_id

答案 1 :(得分:0)

使用union运算符,它会将两个查询放入一个表

http://dev.mysql.com/doc/refman/5.0/en/union.html

答案 2 :(得分:0)

我不确定预订日期

SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS bookingdate, 
  COUNT(b.list_id) AS bookings_lastmonth, COUNT(c.list_id) AS bookings_currentmonth
FROM restaurants r 
LEFT JOIN booking b ON r.list_id = b.list_id AND b.bookingdate BETWEEN 1383224400 AND 1385730000 
LEFT JOIN booking c ON r.list_id = c.list_id AND c.bookingdate BETWEEN 1385816400 AND 1388408400
GROUP BY r.list_id
HAVING bookings_lastmonth>0 OR bookings_currentmonth>0

答案 3 :(得分:0)

不知何故,它通过此查询工作

SELECT t1.list_id, t1.name, t1.city, t1.bookings AS bookings_lastmonth, t2.bookings AS bookings_currentmonth 
FROM   (SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS 'bookingdate', COUNT(*) AS bookings 
        FROM   booking b JOIN restaurants r ON r.list_id = b.list_id 
        WHERE  b.bookingdate BETWEEN 1383224400 AND 1385730000 
        GROUP  BY b.list_id) AS t1

        JOIN (SELECT b.list_id, r.name, r.city, FROM_UNIXTIME(b.bookingdate, '%Y-%m-%d- %h:%i:%s') AS 'bookingdate', COUNT(*) AS bookings 
        FROM   booking b JOIN restaurants r 
        ON r.list_id = b.list_id 
        WHERE  b.bookingdate BETWEEN 1385816400 AND 1388408400 
        GROUP  BY b.list_id) AS t2 

        ON t1.list_id = t2.list_id 

但我仍然需要为更多的工作而努力