use*_*055 1 sql t-sql information-schema left-join
我正在尝试通过在 COLUMN_NAME = COLUMN_NAME 上的 Information_schema 上使用自联接来查找一个表中存在但另一个表中不存在的所有列,并且它是内部联接本身。我似乎无法弄清楚我的逻辑有什么问题:
select c.Column_name, c2.Column_name
from information_schema.columns c
left outer join Information_Schema.Columns c2
ON c.COLUMN_NAME = c2.column_name
Where c.TABLE_NAME = 'Table1'
and c2.TABLE_NAME = 'Table2'
Run Code Online (Sandbox Code Playgroud)
我应该得到
Col1(a) | Col1(b)
Col2(a) | null
Col3(a) | Col3(b)
Col4(a) | Col4(b)
Col5(a) | null
Run Code Online (Sandbox Code Playgroud)
但相反我得到
Col1(a) | Col1(b)
Col3(a) | Col3(b)
Col4(a) | Col4(b)
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
左联接右表上的过滤器应仅在 ON 子句内。当在 where 子句中指定它们时,您的左连接会自动变成内连接。
select c.Column_name, c2.Column_name
from information_schema.columns c
left outer join Information_Schema.Columns c2
ON c.COLUMN_NAME = c2.column_name AND c2.TABLE_NAME = 'Table2'
Where c.TABLE_NAME = 'Table1'
Run Code Online (Sandbox Code Playgroud)