V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
daijinming
V2EX  ›  程序员

请教一个联合查询SQL语句

  •  
  •   daijinming · 2018-09-26 14:37:40 +08:00 · 1343 次点击
    这是一个创建于 2047 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有四个表,一个主表(A),三个从表(B1,B2,B3),当 主表(A) 中 type=1,B1 中有条记录和 A 对应,type=2,B2 中有条记录和 A 对应,type=3,B3 中有条记录和 A 对应。

    A 表结构 AID,TYPE,TITLE

    B1,B2,B3 表结构 BID,AID,BCODE

    需要创建一个 SQL 语句查询以 A 表为主的记录,需要关联出 B1,B2,B3 中的 BCODE

    高手指教

    3 条回复    2018-09-26 15:40:06 +08:00
    moresteam
        1
    moresteam  
       2018-09-26 14:47:45 +08:00   ❤️ 1
    select a.AID,a.TYPE,a.TITLE,b1.BCODE from A a LEFT join B1 b1 on a.AID=b1.AID where a.TYPE=1
    union all
    select a.AID,a.TYPE,a.TITLE,b2.BCODE from A a LEFT join B2 b2 on a.AID=b2.AID where a.TYPE=2
    union all
    select a.AID,a.TYPE,a.TITLE,b3.BCODE from A a LEFT join B3 b3 on a.AID=b3.AID where a.TYPE=3
    justfindu
        2
    justfindu  
       2018-09-26 14:55:36 +08:00   ❤️ 1
    SELECT
    a.*,
    b1.bcode AS b1_code,
    b2.bcode AS b2_code,
    b3.bcode AS b3_code
    FROM
    a
    LEFT JOIN b1 ON b1.aid = a.id
    AND a.type = 1
    LEFT JOIN b2 ON b2.aid = a.id
    AND a.type = 2
    LEFT JOIN b3 ON b3.aid = a.id
    AND a.type =3
    daijinming
        3
    daijinming  
    OP
       2018-09-26 15:40:06 +08:00
    参考两位的 SQL 语句,CSharp 高级开发交流群 256718021 中七爷和 Knight 给出了完善的 SQL 语句

    ~~~
    SELECT
    a.*,
    COALESCE(B1.BCODE,B2.BCODE,B3.BCODE) BCODE
    FROM
    a
    LEFT JOIN b1 ON b1.aid = a.id
    AND a.type = 1
    LEFT JOIN b2 ON b2.aid = a.id
    AND a.type = 2
    LEFT JOIN b3 ON b3.aid = a.id
    AND a.type =3
    ~~~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2338 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:52 · PVG 18:52 · LAX 03:52 · JFK 06:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.