使用UNION模拟FULL JOIN时缺少列

时间:2019-07-04 10:50:56

标签: mysql join union

我有两个表,分别是“ db_product”和“ db_trans_detail”。

db_product
+---------+-------------+---------------+--------+
| number  | product_id  | product_name  | price  |
+---------+-------------+---------------+--------+
|       1 | prod-01     | aaaaaa        |  20    |
|       2 | prod-02     | bbbbbb        |  30    |
|       3 | prod-03     | cccccc        |  45    |
|       4 | prod-04     | dddddd        |  10    |
|       5 | prod-05     | eeeeee        |  25    |
+---------+-------------+---------------+--------+

db_trans_detail
+----------------+-------------+------+
| trans_detail   | product_id  | qty  |
+----------------+-------------+------+
| tr-0001        | prod-04     |    3 |
| tr-0001        | prod-02     |    1 |
| tr-0002        | prod-03     |    2 |
| tr-0003        | prod-04     |    1 |
| tr-0004        | prod-01     |    1 |
| tr-0005        | prod-05     |    1 |
+----------------+-------------+------+

我试图实现的是一个显示“ product_id”,“ product_id”和“ total_qty”列的表。我使用

过滤了每个表
SELECT product_id, COUNT(qty) AS total_qty FROM db_trans_detail
GROUP BY product_id;

SELECT product_id, product_name FROM db_product;

他们工作正常。

当我尝试使用UNION模拟FULL JOIN时,缺少“ product_name”列。

SELECT a.product_id, COUNT(a.qty) AS total_qty FROM db_trans_detail a 
LEFT JOIN (SELECT product_id, product_name FROM db_product) b 
ON a.product_id = b.product_id
GROUP BY product_id
UNION
SELECT a.product_id, COUNT(a.qty) AS total_qty FROM db_trans_detail a 
RIGHT JOIN (SELECT product_id, product_name FROM db_product) b 
ON a.product_id = b.product_id
GROUP BY product_id

我得到的输出

+-------------+------------+
| product_id  | total_qty  |
+-------------+------------+
| prod-01     |  1         |
| prod-02     |  1         |
| prod-03     |  2         |
| prod-04     |  5         |
| prod-05     |  1         |
| NULL        |  0         |
+-------------+------------+

虽然我希望是

+-------------+---------------+---------+
| product_id  | product_name  |total_qty|
+-------------+---------------+---------+
| prod-01     | aaaaaa        |  1      |
| prod-02     | bbbbbb        |  1      |
| prod-03     | cccccc        |  2      |
| prod-04     | dddddd        |  5      |
| prod-05     | eeeeee        |  1      |
+-------------+---------------+---------+

感谢您的帮助。

0 个答案:

没有答案