mysql - SQL 查询 : get data from multiple table with joining each other with common field but no guarantee any table have data for sure.

标签 mysql sql join

<分区>

我想通过公共(public)字段从多个表中获取数据,但没有表保证其中包含数据。

下面的示例将消除混淆:

表A

 commonId       aName
   2              2AName
   5              5AName
   8              8AName

表B

 commonId       bName
   3              3BName
   8              8BName

表C

 commonId       cName
   1              1CName
   2              2CName
   3              3CName

根据以上可用数据,我们需要以下方式的数据:

commonId,   aName,      bName,      cName
  1          NULL        NULL        1CName
  2          2AName      NULL        2CName
  3          NULL        3BName      3CName 
  5          5AName      NULL        NULL
  8          8AName      8BName      NULL

谢谢。

最佳答案

您想要的是全外连接,而 MySQL 不支持。我建议使用 union allgroup by 来解决这个问题:

select commonId,
       max(aName) as aName, max(bName) as bName, max(cName) as cName)
from ((select commonId, aName, NULL as bName, NULL as cName
       from tableA
      ) union all
      (select commonId, NULL as aName, bName, NULL as cName
       from tableB
      ) union all
      (select commonId, NULL as aName, NULL as bName, cName
       from tableC
      )
     ) abc
group by CommonId;

这假设您在表格中没有任何重复项。如果可能的话,您需要解释在这种情况下结果会是什么样子。

关于mysql - SQL 查询 : get data from multiple table with joining each other with common field but no guarantee any table have data for sure.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32759586/

相关文章:

MySql 添加到数据库中的现有条目

php - SQL:特定项目的用户禁止列表

.net - .Net 中的反射可以通过查看用户定义的类型名称来帮助动态构建表值参数/SqlMetaData [] 对象吗?

join - 是否有 clojure 函数来 "join"两个映射列表?

javascript - jquery - 找到整数或空格时拆分(即拆分类(class)代码)

mysql - INPUT INTO 错误 - 初学者 MYSQL 语法问题

mysql 选择计数 = 0 的地方

MySQL 查询选择最近的城市

带有超大 IN 子句的 SQL Server 查询会导致事件监视器中出现大量查询

mysql - 使用 MySQL 连接表和透视数据