从2个不同的表中选择多个列并计算所选列

时间:2019-04-09 04:15:54

标签: mysql

您能教我有关mysql代码的问题吗?问题如下。

查询A

SELECT gbp_sender_date,COUNT(*) AS total_post
FROM guestbook_post
GROUP BY gbp_sender_date DESC;

查询B

SELECT v_date, COUNT(*) AS total_view
FROM visitor_detail_2 
GROUP BY v_date DESC;

查询C

SELECT v.v_date, g.gbp_sender_date
FROM visitor_detail_2 v
LEFT JOIN guestbook_post g ON v.v_date = g.gbp_sender_date
GROUP BY v.v_date DESC;

输出查询A

----------------------------
gbp_sender_date| total post |

----------------------------
2019-04-09     |    5

2019-04-08     |    22   

2019-04-05     |     5

2019-04-04     |     5

2019-04-03     |     5

2019-04-02     |     5

2019-04-01     |     5

-----------------------------

输出查询B

----------------------------
v_date         | total view

----------------------------
2019-04-09     |     9

2019-04-08     |     8

2019-04-05     |     5

2019-04-04     |     4

2019-04-03     |     3

2019-04-02     |     2

2019-04-01     |     1

-----------------------------

问题是我该如何更改查询C中的代码,以便获得预期的输出

---------------------------------------------------------
gbp_sender_date| total post |   v_date       | total view

---------------------------------------------------------
2019-04-09     |     5      | 2019-04-09     |     9      

2019-04-08     |    22      | 2019-04-08     |     8      

2019-04-05     |     5      | 2019-04-05     |     5      

2019-04-04     |     5      | 2019-04-04     |     4      

2019-04-03     |     5      | 2019-04-03     |     3      

2019-04-02     |     5      | 2019-04-02     |     2      

2019-04-01     |     5      | 2019-04-01     |     1      

----------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

从查询C中获得所需结果的一种方法是一起进行JOIN查询A和查询B:

SELECT g.*, v.*
FROM (SELECT gbp_sender_date,COUNT(*) AS total_post
      FROM guestbook_post
      GROUP BY gbp_sender_date) g
JOIN (SELECT v_date, COUNT(*) AS total_view
      FROM visitor_detail_2 
      GROUP BY v_date) v ON v.v_date = g.gbp_sender_date
ORDER BY g.gbp_sender_date DESC