如何在一个输出中合并两个mysql表的结果

时间:2014-04-03 16:30:04

标签: mysql sql

我有两个类似的mysql表,想要在一个输出(合并)中从两个数据中获取数据。我该怎么办?

出于这个原因,我创建了两个单独的查询来检查我是否得到了我正在寻找的内容。

首先:表格 - > web_session

SELECT date_format(booking_time, '%m-%Y') AS m, count(booking_time) AS b
FROM web_session
WHERE
  date(booking_time) >= date_sub(curdate(), interval 12 month)
AND
  date(booking_time) <= date_add(curdate(), interval 6 month)
GROUP BY month(booking_time)
ORDER BY booking_time ASC;

输出:

m, b
10-2013, 15
11-2013, 6
12-2013, 13
01-2014, 10
02-2014, 10
03-2014, 25
04-2014, 1

第二:表 - &gt; web_log

SELECT date_format(request_time, '%m-%Y') AS m, count(request_time) AS r
FROM web_log
WHERE
  date(request_time) >= date_sub(curdate(), interval 12 month)
AND
  date(request_time) <= date_add(curdate(), interval 6 month)
GROUP BY month(request_time)
ORDER BY request_time ASC;

输出:

m, r
03-2014, 45
04-2014, 35

所需的输出:

m, b, r
10-2013, 15, null
11-2013, 6,  null
12-2013, 13, null
01-2014, 10, null
02-2014, 10, null
03-2014, 25, 45
04-2014, 1,  35

1 个答案:

答案 0 :(得分:1)

你需要加入他们。试试这个:

SELECT T1.m,T1.b,T2.r FROM
(
SELECT date_format(booking_time, '%m-%Y') AS m, count(booking_time) AS b
FROM web_session
WHERE
  date(booking_time) >= date_sub(curdate(), interval 12 month)
AND
  date(booking_time) <= date_add(curdate(), interval 6 month)
GROUP BY month(booking_time)
ORDER BY booking_time ASC;) T1

LEFT OUTER JOIN

(SELECT date_format(request_time, '%m-%Y') AS m, count(request_time) AS r
FROM web_log
WHERE
  date(request_time) >= date_sub(curdate(), interval 12 month)
AND
  date(request_time) <= date_add(curdate(), interval 6 month)
GROUP BY month(request_time)
ORDER BY request_time ASC;) T2

ON T1.m=T2.m
ORDER BY T1.m

输出将是:

m          b      r
10-2013    15     null
11-2013    6      null
12-2013    13     null
01-2014    10     null
02-2014    10     null
03-2014    25     45
04-2014    1      35