gpt4 book ai didi

sql-server - SQL Server 条件 JOIN 语句

转载 作者:行者123 更新时间:2023-12-01 18:01:14 24 4
gpt4 key购买 nike

是否可以执行以下操作:

IF [a] = 1234 THEN JOIN ON TableA 
ELSE JOIN ON TableB

如果是这样,正确的语法是什么?

最佳答案

我认为您所要求的内容可以通过使用LEFT JOIN<将Initial表连接到Option_AOption_B来实现,这将产生如下内容:

Initial LEFT JOIN Option_A LEFT JOIN NULL
OR
Initial LEFT JOIN NULL LEFT JOIN Option_B

示例代码:

SELECT i.*, COALESCE(a.id, b.id) as Option_Id, COALESCE(a.name, b.name) as Option_Name
FROM Initial_Table i
LEFT JOIN Option_A_Table a ON a.initial_id = i.id AND i.special_value = 1234
LEFT JOIN Option_B_Table b ON b.initial_id = i.id AND i.special_value <> 1234

完成此操作后,您将“忽略”NULL 集。这里的额外技巧是在 SELECT 行中,您需要决定如何处理 NULL 字段。如果 Option_A 和 Option_B 表相似,则可以使用 COALESCE 函数返回第一个 NON NULL 值(按照示例)。

另一个选项是,您只需列出 Option_A 字段和 Option_B 字段,并让使用 ResultSet 的任何内容来确定要使用哪些字段。

关于sql-server - SQL Server 条件 JOIN 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com