如何在SQL中将数据与不同的表合并

时间:2015-10-08 06:44:08

标签: php mysql sql join

我有3个不同的表,我想合并来自不同表格的相同发票号的数据库

我尝试了一些代码,但我有不同的输出。 我的示例表

表1

enter image description here

表2

enter image description here

表3

enter image description here

我的查询与输出

enter image description here

MY DESIRE OUTPUT

enter image description here

1 个答案:

答案 0 :(得分:1)

首先创建一个混合表1和表2的视图

CREATE VIEW `view 1 2` AS
  SELECT `table 1`.invoice_no, `table 1`.shoe_brand, `table 2`.clothing_brand
    FROM `table 1` LEFT  JOIN `table 2`
    ON `table 1`.invoice_no = `table 2`.invoice_no
UNION
  SELECT `table 2`.invoice_no, `table 1`.shoe_brand, `table 2`.clothing_brand
    FROM `table 1` RIGHT JOIN `table 2`
    ON `table 1`.invoice_no = `table 2`.invoice_no;

然后创建一个视图,将'view 1 2'与'table 3'混合

CREATE VIEW `view 1 2 3` AS
  SELECT `view 1 2`.invoice_no, `view 1 2`.shoe_brand, `view 1 2`.clothing_brand, `table 3`.watch_brand
    FROM `view 1 2` LEFT  JOIN `table 3`
    ON `view 1 2`.invoice_no = `table 3`.invoice_no
UNION
  SELECT `table 3`.invoice_no, `view 1 2`.shoe_brand, `view 1 2`.clothing_brand, `table 3`.watch_brand
    FROM `view 1 2` RIGHT JOIN `table 3`
    ON `view 1 2`.invoice_no = `table 3`.invoice_no

现在是一个简单的SELECT * FROM view 1 2 3;返回结果,并将工作留给MySQL。

+------------+------------+----------------+-------------+
| invoice_no | shoe_brand | clothing_brand | watch_brand |
+------------+------------+----------------+-------------+
|          1 | Nike       | GAP            | Omega       |
|          2 | Addidas    | OLD NAVY       | NULL        |
|          3 | Sperry     | NULL           | NULL        |
|          5 | NULL       | Puma           | Seiko       |
|          4 | NULL       | NULL           | Casio       |
+------------+------------+----------------+-------------+