SQL server Left join 子表并获取表名

标签 sql sql-server

假设我们有一个 Instrument 表,其子表 Equity 和 Bond 具有外键 InstrumentId。每个仪器在其中一个子表中都有唯一的记录。

是否可以使用左连接创建一个 View ,以查看所有仪器的列包含存在记录的表名?

SELECT        Instrument.InstrumentId, Instrument.Name, ***CHILD_TABLE_NAME***
FROM          Instrument
LEFT OUTER JOIN
              Equity ON Equity.InstrumentId = Instrument.InstrumentId 
LEFT OUTER JOIN
              Bond ON SBond.InstrumentId = Instrument.InstrumentId 

另一种方法是建立内部连接的并集:

SELECT instrumentId, Name, instrumentType 
FROM
(SELECT Instrument.instrumentId, Name, 'Equity' as instrumentType FROM dbo.Equity inner join Instrument on Instrument.InstrumentId = Equity.InstrumentId
UNION
SELECT Instrument.instrumentId, Name, 'Bond' as instrumentType from dbo.Bond inner join Instrument on Instrument.InstrumentId = Bond.InstrumentId) u

最佳答案

一个选择是像这样在你的连接中包含表名

SELECT i.InstrumentId, 
       i.Name, 
       e.TableEquity,
       b.TableBond
FROM Instrument i 
  LEFT OUTER JOIN (select 'Equity' as TableEquity from Equity) e
    ON i.InstrumentId = e.InstrumentId 
  LEFT OUTER JOIN (select 'Bond' as TableBond from Bond) b
    ON i.InstrumentId = b.InstrumentId

由@sofsntp 编辑:将股票/债券合并到一列中

SELECT i.InstrumentId, 
       i.Name, 
       (ISNULL(e.TableEquity,'') + ISNULL(b.TableBond ,''))
FROM Instrument i 
  LEFT OUTER JOIN (select *, 'Equity' as TableEquity from Equity) e
   ON e.InstrumentId = i.InstrumentId 
 LEFT OUTER JOIN (select *, 'Bond' as TableBond  from StraightBond) b
   ON b.InstrumentId = i.InstrumentId

关于SQL server Left join 子表并获取表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51379920/

相关文章:

sql - 如何将表列标题添加到sql select语句

sql-server - 在 SQL Server 2014 中备份维护计划或作业

sql - 奇怪的 ORA-00907 : missing right parenthesis

MySQL查询搜索2列共享相同1列的所有列

sql - 返回字符串中的单词 - SQL

sql-server - 消息 319,级别 15,状态 1, "Incorrect syntax near the keyword ' 带有“。”

SQL 查询根据同一表中其他列的值更新列

sql - 没有双结果集的自连接?

sql - 如何授予用户对 SQL Server 中数据库的读取访问权限?

sql - 日期在不同服务器上显示不同