如何使用条件进行内连接...?

时间:2012-10-24 08:46:23

标签: sql sql-server sql-server-2000

SQL Server 2000

使用超过20个视图,所有视图都是与table1的内连接(id和value1和value2)

表1

ID Value1 Value2

001 100 null
001 200 null
001 300 null
001 400 null
001 200 null

ID Value1 Value2

001 null 100 
001 null 200 
001 null 300 
001 null 400 
001 null 200 

表2

ID value1 value2

....
....

some data's
从table1

,value1或value2应始终为null。现在的问题是,如果 value1或value2列为null,则输出显示为null,因为所有视图都是内部连接,其id为,value1,value2

我想用条件进行内部连接,如果value1不为null,则使用内部连接 value1或者value2不为null,则内连接为value2

像这样查询

Select * from table2 inner join with table1 on tabel2.id = table1.id and if table1.value1 is null then table2.value2 = table1.value2 or
else table2.value1 = table1= value1 end if

如何查询上述条件

需要SQL查询帮助

4 个答案:

答案 0 :(得分:1)

以下是否会有以下工作?

SELECT * FROM table2
INNER JOIN WITH table1 ON table2.id = table1.id
    AND (table1.value1 = table2.value1 OR table1.value1 IS NULL)
    AND (table1.value2 = table2.value2 OR table1.value2 IS NULL)

我认为如果你有一个大数据集,这可能会很慢......

答案 1 :(得分:0)

您是否尝试过coalesce(value1, value2)

答案 2 :(得分:0)

试试这个解决方案:

Select * 
from table2 
inner join table1 on (tabel2.id = table1.id 
                      and table1.value1 is null 
                      and table2.value2 = table1.value2) 
                  or ( table2.value1 = table1.value1 )

答案 3 :(得分:0)

SELECT * FROM table2 t2
INNER JOIN WITH table1 t1 ON table2.id = table1.id
On (CASE WHEN t1.value1 is null then t1.value2=t2.value2 else t1.value1=t2.value1)
and
(CASE WHEN t2.value1 is null then t2.value2=t1.value2 else t2.value1=t1.value1)