唯一的其他真正的替代解決方案是在拉與IN
子句相關的記錄並利用CASE
語句將用戶名與正確的user_id綁定。然而,這比簡單地使用JOIN
聲明更復雜,除了沒有涉及多個JOIN
之外,並沒有真正提供任何優勢。下面是一個如何使用這種結構提取數據的完整工作示例:
create table #temp
(
one_user_id int,
two_user_id int,
three_user_id int,
four_user_id int,
one_username varchar(50),
two_username varchar(50),
three_username varchar(50),
four_username varchar(50)
)
insert #temp (one_user_id, two_user_id, three_user_id, four_user_id) values (1, 3, 6, 7)
insert #temp (one_user_id, two_user_id, three_user_id, four_user_id) values (2, 5, 8, 1)
;with User_Lookup as (
select 1 as user_id, 'abc' as username union
select 2, 'def' union
select 3, 'ghi' union
select 4, 'jkl' union
select 5, 'mno' union
select 6, 'pqr' union
select 7, 'stu' union
select 8, 'vwx' union
select 9, 'jon' union
select 10, 'bob'
), Result as (
select
one_user_id,
two_user_id,
three_user_id,
four_user_id,
max(case when U.user_id = one_user_id then U.username end) as one_username,
max(case when U.user_id = two_user_id then U.username end) as two_username,
max(case when U.user_id = three_user_id then U.username end) as three_username,
max(case when U.user_id = four_user_id then U.username end) as four_username
from
#Temp T,
User_Lookup U
where
U.user_id in (T.one_user_id, T.two_user_id, T.three_user_id, T.four_user_id)
group by
T.one_user_id, T.two_user_id, T.three_user_id, T.four_user_id
)
update
#temp
set
one_username = R.one_username,
two_username = R.two_username,
three_username = R.three_username,
four_username = R.four_username
from
Result R
inner join
#temp T on R.one_user_id=T.one_user_id and R.two_user_id=T.two_user_id
and R.three_user_id=T.three_user_id and R.four_user_id=T.four_user_id
select * from #temp
drop table #temp
輸出:
one_user_id two_user_id three_user_id four_user_id one_username two_username three_username four_username
1 3 6 7 abc ghi pqr stu
2 5 8 1 def mno vwx abc
你需要或者'JOIN'多次或修復您的表設計。 – JNK
我說我知道我可以加入多次,我正在尋找替代品 – Ian
@Ian:JNK的觀點是沒有重新設計你的'#temp'表格結構就沒有別的選擇。 –