繁体   English   中英

有特定条件的左联接

[英]LEFT JOIN with a specific condition

我有两张桌子

table A
---------
uid   c1(distinct)
---------
 1     a
 1     b
 2     c
 3     d
 3     e
 3     f
 4     g

table B
---------
uid   c2(non unique)
---------
 1     x
 2     y
 3     z
 3     z  
 3     v

我需要这样的结果表,将表A映射到uid上的表B

Result Table
-------------
uid   c1   c2
-------------
 1     a    x
 1     b    -
 2     c    y
 3     d    z
 3     e    z
 3     f    v
 4     g    -

基本上,一旦在结果表中使用了表B中的一行,就必须将其耗尽。 在这种情况下,任何JOINS都不起作用。

这两个表都包含大量记录,因此我无法为每个uid编写单独的查询。

让我们计算具有相同uid的行,并连接相等的uid和该数字

select t.uid, c1, ifnull(c2, '-') c2 
    from 
      (select *, @n:=if(@i=uid, @n+1, if(@i:=uid, 1, 1)) n 
           from tableA 
               cross join 
                (select @n:=0, @i:='') param1 
          order by uid
      ) t 
    left join 
      (select *, @n1:=if(@i1=uid, @n1+1, if(@i1:=uid, 1, 1)) n1 
           from tableB 
               cross join 
                (select @n1:=0, @i1:='') param2 
         order by uid
      ) tt 
          on t.uid=tt.uid and t.n=tt.n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM