JOIN根據連接列是否為表,最好的方法是NULL什么。
我需要與JOINtable#main同桌#sub。
例如:
如果ID表#main中的NULL列然后加入列LocationID= #sub.LocationID
如果表中ID的LocationID列#main是NULLs 則加入列UserID=#sub.UserID
create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
(2,NULL,'User1'),
(NULL,'Loc1','User1'),
(4,'Loc1',NULL),
(5,NULL,'User1'),
(NULL,'Loc1','User1')
--select * from #main
select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on m.UserID = s.UserID
left join #sub s ON m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID
謝謝
uj5u.com熱心網友回復:
像這樣的東西應該作業。不知道性能...
Select * From #Main m
left Join #sub s on
(m.id is null and m.locationid is null and m.userId = s.userID)
or (m.id is not null and m.locationid is null and m.locationid = s.locationId)
or (m.id is not null and m.locationid is not null and m.id = s.id)
uj5u.com熱心網友回復:
查詢每個條件并合并結果,例如
select *
from #main m
left join #sub s on s.locationId = m.LocationId
where m.Id is null and m.locationId is not null
union all
select *
from #main m
left join #sub s on s.UserId - m.UserId
where m.Id is null and m.locationId is null
uj5u.com熱心網友回復:
我不確定您是否想要join或left join(您在問題中提到了兩者),因此請根據您的需要修改以下代碼:
select ...
from #main m
join #sub s on m.id = s.id
or (m.id is null and and m.locationId = s.locationId)
or (m.id is null and m.locationId is null and m.userId = s.userId)
我使用了null這里的一個特性來縮短語法:null不等于任何東西。它甚至不等于null。因此,在m.id列上進行連接時,您似乎必須這樣做:
on m.id is not null and m.id = s.id
但是如果m.id是 null,那么它永遠不會等于s.id,因為null不等于任何東西。所以你可以做
on m.id = s.id
因為那個條件只有在不滿足的時候才能m.id滿足null。我對locationId連接條件使用了類似的骯臟技巧。
但是,包含or條件的連接通常非常慢,有時向 SQL Server 解釋同樣的問題可以用union連接不包含or操作,僅包含操作的操作來表述是有幫助的and:
select ...
from #main m
join #sub s on m.id = s.id
union all
select ...
from #main m
join #sub s on m.id is null
and m.locationId = s.locationId
union all
select ...
from #main m
join #sub s on m.id is null
and m.locationId is null
and m.userId = s.userId
uj5u.com熱心網友回復:
作為 的替代方法join,這可以使用outer apply子查詢來完成,其中匹配條件通過case when如下方式實作:
Select *
From #main As m Outer Apply
(Select * From #sub As s
Where 1 = Case When m.ID Is Not Null And m.ID=s.ID Then 1
When m.ID Is Null And m.LocationID Is Not Null And m.locationID=s.locationID Then 1
When m.ID Is Null And m.LocationID Is Null And m.UserID Is Not Null And m.UserID=s.UserID Then 1
Else 0
End) As t
Order by m.ID, m.locationID, m.UserID
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/425362.html
