• 请不要在回答技术问题时复制粘贴 AI 生成的内容
daijinming
V2EX  ›  程序员

请教一个联合查询SQL语句

  •  
  •   daijinming · Sep 26, 2018 · 1768 views
    This topic created in 2810 days ago, the information mentioned may be changed or developed.

    现在有四个表,一个主表(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 replies    2018-09-26 15:40:06 +08:00
    moresteam
        1
    moresteam  
       Sep 26, 2018   ❤️ 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  
       Sep 26, 2018   ❤️ 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
       Sep 26, 2018
    参考两位的 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
    ~~~
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1007 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:16 · PVG 07:16 · LAX 16:16 · JFK 19:16
    ♥ Do have faith in what you're doing.