根据SQL Server中的列值连接表

时间:2017-07-31 12:32:39

标签: sql sql-server join

项目

id  key code    description
------------------------------
1   1   misc    miscellaneous
2   1   med     medicine    

其他表:

id  code    description
------------------------
1   misc1   miscellaneous
2   misc1   miscellaneous

医学表:

id  code        description
---------------------------
1   medicine1   medicine
2   medicine1   medicine

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

我知道

这个表的基本JOIN
SELECT * 
FROM item 
INNER JOIN miscellaneous ON item.key = miscellaneous.id

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

3 个答案:

答案 0 :(得分:3)

您可以使用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';

答案 1 :(得分:0)

您可以尝试使用LEFT JOIN,这是实现此目的最简单的方法。 但是,如果您希望表格结果都在一个列名称下,请使用UNION ALL

使用UNION ALL

SELECT *
FROM item i
INNER JOIN miscellaneous m on m.code=i.code
UNION ALL
SELECT *
FROM item i
INNER JOIN medicine  me on me.code=i.code

使用LEFT JOIN

SELECT *
FROM item i
LEFT JOIN miscellaneous m on m.code=i.code
LEFT JOIN medicine  me on me.code=i.code

答案 2 :(得分:0)

由于 Item 是您的'base'/ main表,您可以使用LEFT JOIN匹配其他表,以便Item表中的所有行都存在。

SELECT * 
FROM Item AS i
LEFT JOIN Miscellaneous AS mi ON (mi.[id] = i.[key] AND i.code = 'misc')
LEFT JOIN Medicine AS me ON (me.[id] = i.[key] AND i.code = 'med');

您还可以将Miscellaneous&使用带有一些前提条件的ISNULL()函数的Medicine表列

SELECT i.*
  , ISNULL(mi.id, me.id) AS m_id
  , ISNULL(mi.code, me.code) AS m_code
  , ISNULL(mi.description, me.description) AS m_description
FROM Item AS i
LEFT JOIN Miscellaneous AS mi ON (mi.id = i.[key] AND i.code = 'misc')
LEFT JOIN Medicine AS me ON (me.id = i.[key] AND i.code = 'med');

SqlFiddle Demo