SQL Server 中基于列值的连接表

Mar*_*tin 4 sql sql-server join

项目

id  key code    description
------------------------------
1   1   misc    miscellaneous
2   1   med     medicine    
Run Code Online (Sandbox Code Playgroud)

杂项表:

id  code    description
------------------------
1   misc1   miscellaneous
2   misc1   miscellaneous
Run Code Online (Sandbox Code Playgroud)

药品表:

id  code        description
---------------------------
1   medicine1   medicine
2   medicine1   medicine
Run Code Online (Sandbox Code Playgroud)

我有这个表结构;我的主表是Item表,我想根据主表中的列值将主表与其他表连接起来。确定要连接的表的列是code。如果代码与misc联接,misc table如果值与med联接medicine table

JOIN我知道表格的基本知识

SELECT * 
FROM item 
INNER JOIN miscellaneous ON item.key = miscellaneous.id
Run Code Online (Sandbox Code Playgroud)

但我不知道当有条件指向哪个表时如何加入JOIN

Gor*_*off 6

您可以使用left join。像这样的东西:

select i.*,
       coalesce(mi.code, me.code) as code_1,
       coalesce(mi.description, me.description) as description_1
from item i left join
     miscellaneous mi
     on mi.code = i.key and i.code = 'misc' left join
     medicine me
     on me.code = i.key and i.code = 'med';
Run Code Online (Sandbox Code Playgroud)