SQL Server NULL 值与内连接
我正在使用 C# 和 SQL Server。
看一下下面的 SQL:
SELECT table1.id, table1.description, table2.name, table2.surname
FROM table1
INNER JOIN table2 ON table1.EmpID = table2.EmpID
它很简单并且运行良好。它可以很好地从 table1 表中检索数据,并正确地将 table1.empid
内部联接到 table2.name
和 table2.surname
。
现在,有时 table1.empid
为 null,当它为 null 时,此 SQL 只是忽略具有 null 值的“行”;根据标准,这是很正常的。
我在这里还需要获取具有空值的“行”,当 table1.empid
为空时,我需要为 table2.name
和 <代码>table2.姓氏。
我一直在玩 isnull() 但我所做的只是让它变得更糟。
有什么建议吗?
谢谢
I am using C# and SQL Server.
Take a look at the following SQL:
SELECT table1.id, table1.description, table2.name, table2.surname
FROM table1
INNER JOIN table2 ON table1.EmpID = table2.EmpID
It is straight forward and works fine. It retrieves the data from table1 table just fine and inner joins table1.empid
to table2.name
and table2.surname
correctly.
Now, sometimes table1.empid
is null and when it is, this SQL just ignores the "row" with the null value; which is pretty normal basing on the criteria.
What I need here is to also get the "rows" with the null values and when table1.empid
is null I need to set a custom value to table2.name
and table2.surname
.
I have been playing with isnull() but all I did is make it even worst.
Any suggestions?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要执行 LEFT JOIN:
You need to do a LEFT JOIN:
尝试使用 UNION:
Try using a UNION:
如果表 1 为空,而您仍然需要无法以此开头的记录。从 table2 开始并连接 table1。
If table 1 is null and you still need the records that you cannot start with that. Start with table2 and join table1.
现在请注意,这还包括当 EmpID 不为空但仍然“无效”时的人员(如果他们在 table1 中有 EmpID,但在 table2 中找不到该 EmpID),所以如果您想避免这种情况,另一个选择是这样:
Now note, that this will also include people when the EmpID is not null but nevertheless "invalid" if they have an EmpID in table1, but it isn't found in table2, so if that's something you want to avoid, another option is this: