Select 具有所需值的 table 的一行,当在关键字的 where 子句中选择了不在 table 中的列的值时?
Select a row of the table with desired value, when a column's value which is not in the table is selected in where clause in keyword?
我有一个 table,其中一列作为 ID。我有一组值,我在 where 子句中给出了使用 'in' 关键字比较 'ID' 列的值。如果该组值中的值在 table 中有记录,我想 select 该行。如果不是,则 table 中不存在的值必须与其他列的空值一起 selected。
例如:
有一个包含 ID 和 Animal 列的 table。它有8条记录。
The table with all records
如果我运行查询:
SELECT ID, Animal from #Temp1 where ID in (4,8)
它将return以下结果。
The table result filtered
但是,如果我 运行 查询:
SELECT ID, Animal from #Temp1 where ID in (4,8,12)
应该return结果如下。
The table result with desired values
改用 LEFT JOIN
和 string_split()
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From string_split('4,8,12',',') A
Left Join YourTable B on A.value=B.ID
结果
ID Animal
4 Donkey
8 Hampster
12 ID Not Found
如果碰巧 string_split() 不可用
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From (values (4)
,(8)
,(12)
) A(value)
Left Join YourTable B on A.value=B.ID
我有一个 table,其中一列作为 ID。我有一组值,我在 where 子句中给出了使用 'in' 关键字比较 'ID' 列的值。如果该组值中的值在 table 中有记录,我想 select 该行。如果不是,则 table 中不存在的值必须与其他列的空值一起 selected。
例如: 有一个包含 ID 和 Animal 列的 table。它有8条记录。
The table with all records
如果我运行查询:
SELECT ID, Animal from #Temp1 where ID in (4,8)
它将return以下结果。
The table result filtered
但是,如果我 运行 查询:
SELECT ID, Animal from #Temp1 where ID in (4,8,12)
应该return结果如下。
The table result with desired values
改用 LEFT JOIN
和 string_split()
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From string_split('4,8,12',',') A
Left Join YourTable B on A.value=B.ID
结果
ID Animal
4 Donkey
8 Hampster
12 ID Not Found
如果碰巧 string_split() 不可用
Select ID = A.value
,Animal = coalesce(B.Animal,'ID Not Found')
From (values (4)
,(8)
,(12)
) A(value)
Left Join YourTable B on A.value=B.ID