Tsql 跨表的T-SQL条件选择
我有一张桌子(我们称之为main_guys),看起来像:Tsql 跨表的T-SQL条件选择,tsql,sqlite,Tsql,Sqlite,我有一张桌子(我们称之为main_guys),看起来像: id, other_item_id, other_item_type, another_column, group_id other\u item\u type告诉我哪个附加表包含由other\u item\u id标识的附加信息 查询中需要的其他列取决于由其他项目类型标识的表。因此,对于other_item\u type==“type-X”我需要从X表的foo列和bar中获取值。而对于other_item_type==type-Y我需
id, other_item_id, other_item_type, another_column, group_id
other\u item\u type
告诉我哪个附加表包含由other\u item\u id
标识的附加信息
查询中需要的其他列取决于由其他项目类型标识的表。因此,对于other_item\u type==“type-X”
我需要从X
表的foo列和bar
中获取值。而对于other_item_type==type-Y
我需要从Y表的ick和blah列中获取值
在一个完美的世界里,我可以得到如下东西:
id、other_item_id、other_item_type、other_列、group_id、foo、bar、ick、blah
——每种类型在需要的地方填写值,其他列为null,如果不需要,则不填写
另一个问题是other_item_type
和other_item_id
也可以为空-该行中的其余列需要在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
感谢您的帮助或建议。您需要查看左侧外部联接
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
你是说像这样的事吗
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'
如果我理解正确,这意味着您在主表的一列中引用了两个(或多个)表。我鼓励您将主表的设计更改为具有一列具有一种含义您可以这样做:
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'
我的方法是在具有硬编码的其他\u item\u类型值的联合上创建集合
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
这取决于您有多少其他类型的不同值,以及需要处理多少值。我认为id列正好相反。十、 你有其他的项目id。是的-完全同意设计问题。。。可悲的是,我正在使用一家不受我控制的商店。谢谢你的解决方案。好东西。@pjp:不是根据OP的伪代码,而是考虑到他已经接受了你的答案,你可能是对的。pjp-你很强硬。消息被意外保存。试试tab+enter!好:)为什么需要外部选择?遗憾的是,我正在读取的数据库不在我的控制之下,因此基于字符串的id:(…感谢您的解决方案。