代码之家  ›  专栏  ›  技术社区  ›  Gabriel

跨表的T-SQL条件选择

  •  1
  • Gabriel  · 技术社区  · 15 年前

    我有一张桌子(我们称之为“主桌子”),看起来像:

    id, other_item_id, other_item_type, another_column, group_id
    

    这个 other_item_type 告诉我哪个附加表包含由 other_item_id .

    查询中所需的其他列取决于 其他单位类型 . 所以 other_item_type == 'Type-X' 我需要从列中获取值 foo bar X 表。而对于 other_item_type == Type-Y 我需要从列中获取值 ick and blah Y table .

    在一个完美的世界里,我可以得到:

    id, other_item_id, other_item_type, another_column, group_id, foo, bar, ick, blah -在每种类型需要的地方填充值,其他列为空,或者不需要时填充值。

    另外一个问题是 其他单位类型 其他项目 也可以为空-该行中的其余列需要在select中返回-但在空的情况下,其他表中的任何附加列都不应包含任何值。

    就伪代码而言…

    // obviously not proper code - just trying to communicate need
    // Note: Need all items from main_guys table - 
    // even if main_guys.other_item_type is empty
    select * from main_guys where main_guys.group_id == "12345" 
    if main_guys.other_item_type == "Type-X"
     select x.foo, x.bar from x where x.id == main_guys.other_item_id
    else if main_guys.other_item_type == "Type-Y" 
     select y.ick, y.bar from y where y.id == main_guys.other_item_id
    

    感谢您的帮助或建议。

    4 回复  |  直到 15 年前
        1
  •  1
  •   pjp    15 年前

    你需要看看 LEFT OUTER JOIN S

    select * from main_guys MG
        left outer join X 
           on MG.id=X.other_item_id and other_item_type='Type-X'
    
        left outer join Y 
           on MG.id=Y.other_item_id and other_item_type='Type-Y'
        where MG.group_id = '12345' --not sure why this is text
    
        2
  •  1
  •   Lieven Keersmaekers    15 年前

    你的意思是这样的吗

    SELECT mg.id, mg.other_item_id, mg.other_item_type, coalesce(x.ick, y.ick)
    FROM main_guys mg
         LEFT OUTER JOIN x ON x.id = mg.Other_Item_ID AND mg.Other_Item_Type = 'Type-X'
         LEFT OUTER JOIN y ON y.id = mg.Other_Item_ID AND mg.Other_Item_Type = 'Type-Y'
    

    如果我理解正确,这意味着在主表的一列中有两个(或多个)表的引用。我鼓励你改变主表的设计 一栏 一个意义 .

        3
  •  1
  •   AdaTheDev    15 年前

    你可以这样做:

    SELECT m.*, x.*, y.*
    FROM main_guys m
        LEFT JOIN x ON m.id=x.other_item_id AND m.other_item_type = 'Type-X'
        LEFT JOIN y ON m.id=y.other_item_id AND m.other_item_type = 'Type-Y'
    
        4
  •  0
  •   Oleg Kalenbet    15 年前

    我的方法是在联合体上创建集合,并像您所拥有的那样使用硬编码的其他\项\类型值。

    select * from 
    (
        select main.*, x.foo as col1, x.bar as col2
        from main_guys as main
        inner join x on x.id == main_guys.other_item_id
        where other_item_type == "Type-X"
        union
        select main.*, y.ick as col1, y.bar as col2
        from main_guys as main
        inner join y on y.id == main_guys.other_item_id
        where other_item_type == "Type-Y" 
    ) as a
    

    它取决于您拥有的其他_item_类型的不同值以及要处理的值的数量。