唯一的其他真正的替代解决方案是在拉与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'表格结构就没有别的选择。 –