php - 如何在SQL中合并不同表的数据

标签 php mysql sql join

我有3个不同的表,我想合并不同表中相同发票号的数据

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

表1

enter image description here

表2

enter image description here

表3

enter image description here

我的查询和输出

enter image description here

我的期望输出

enter image description here

最佳答案

首先创建一个 View 来混合表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 以混合“ View 1 2”与“表 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       |
+------------+------------+----------------+-------------+

关于php - 如何在SQL中合并不同表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008428/

相关文章:

SQL 获取出现一次的值,而不是不同的值

sql - 在没有循环的情况下在 SQL 中添加迄今为止的工作日

php adodb MSSQL 连接

php - 如何检查php系统函数执行时是否没有任何错误?

php - SQL 查询对于另一个 mysql 版本执行速度较慢?

php - 使用curl : 500 internal server error调用我的php脚本时无法将json数据添加到mysql数据库中

mysql - 创建包含另一个表的列并计算另一个表的值的表

php - 如果有多个字段,则重复键更新

php - 事件类不显示声明的 css

php - 使用 foreach 循环时,限制查询在 codeigniter 中不起作用