mysql - 两个表的左外连接

标签 mysql sql

我有一个与表 2 具有一对多关系的表 1。 表1与表3也存在一对多关系

我想合并连接的结果,但我得到的都是重复值

结构如下:

table 1
reportnumber
1
2
3

table 2
reportnumber  col1
1              a
1              b
2              c
3              a

table 3
reportnumber  col2
1              x
1              y
1              z
2              w

预期结果集

reportnumber   col1   col2
1                a      x
1                b      y
1                       z
2                c      w
3                a

我确信这可以通过左外连接实现,但我只是无法获得正确的语法

有什么线索吗?

这就是我正在尝试的

select * from table1 a 
left outer join table2 b on a.reportnumber=b.reportnumber
left outer join table3 on a.reportnumer=c.reportnumber 

但是结果是这样的

reportnumber   col1   col2
1               a       x
1               a       y
1               a       z
1               b       x
1               b       y
1               b       z
...

最佳答案

这在 MySQL 中并不容易,但您可以使用变量来做到这一点。这与join关系不大。或者,它与join有很大关系,但您没有正确的join键并且没有完全外部联接 >.

解决方案是使用数据列枚举每个表中的行。然后使用枚举和reportnumber进行聚合:

select reportnumber, max(col1) as col1, max(col2) as col2
from ((select t2.reportnumber, col1, null as col2, @rn2 := @rn2 + 1 as rn
       from table2 t2 cross join
            (select @rn2 := 0) const
      ) union all
      (select t3.reportnumber, null, t3.col2, @rn3 := @rn3 + 1 as rn
       from table3 t3 cross join
             (select @rn3 := 0) const
      )
     ) t
group by reportnumber, rn;

关于mysql - 两个表的左外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672612/

相关文章:

mysql - 最佳实践 : mysql remote mobile devices sync over 3G connection

c++ - C++面向对象程序中MySQL连接的实现

c# - SQL Server 2008 错误 - XML 分析 : document parsing required too much memory

php - 获取 2 个不同日期的数据并进行比较

MySQL:提取上周和前一周的总计

mysql - 如果发现一个逗号分隔记录与另一逗号分隔记录匹配,则获取记录

sql - JOIN 与 EXISTS 性能

MySQL平均连接表

sql - 选择已分组的 2 条记录,然后将它们并排放置在 2 列中

MySQL 对多个表进行排序需要很长时间