简体   繁体   English

基于if条件的SQL连接表

[英]SQL join tables based on if else if conditions

New to doing SQL stuff so please excuse me. SQL知识的新手,请原谅。

I want to create a SQL query that joins a column to table A from table B based on the following match logic: 我想基于以下匹配逻辑创建一个将查询从表B连接到表A的SQL查询:

B.Source = ‘SOURCE1’ and A.NameCode= B.Code

If the above return NULL then I'd like to match on: 如果以上返回NULL,那么我想匹配:

B.Source <> ‘SOURCE1’ and A.UEN = B.UEN**

Any help on how to structure this? 任何有关如何构建此结构的帮助? I currently have a union all select query that can get the values based on the above conditions. 我目前有一个联合所有选择查询,可以根据上述条件获取值。 Should I be using an If/or/case_when in the join process? 我应该在加入过程中使用If / or / case_when吗?

A few questions in which I thought could be helpful and that I've looked at are: 我认为可能会有所帮助的几个问题是:

How to perform a LEFT JOIN in SQL Server between two SELECT statements? 如何在SQL Server中的两个SELECT语句之间执行LEFT JOIN?

Using IS NULL or IS NOT NULL on join conditions - Theory question 在连接条件上使用IS NULL或IS NOT NULL-理论问题

But I was not able to come up with anything :( Thank you so much! 但是我什么也没想起来:(非常感谢!

Try something like this: 尝试这样的事情:

SELECT * 
FROM A
JOIN B ON (
    (B.Source = 'Source1' AND A.NameCode = B.Code) OR
    (B.Source <> 'Source1' AND A.UEN = B.[UEN**]) --Not sure what the ** is?  Part of the field name?
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM