dongmeiwei0226 2015-09-03 13:32
浏览 285
已采纳

LEFT JOIN具有特定条件

I have two tables

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

and

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

I need a resultant table which maps table A to table B on uid like this

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

Basically once a row from table B is used in the resultant table, it must be exhausted. None of the JOINS work in this case.

Both these tables contain large number of records, so I can't write individual queries for each uid.

  • 写回答

1条回答 默认 最新

  • douyun7285 2015-09-03 13:49
    关注

    Let's count the rows with the same uid and join equal uids and that numbers

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?