简体   繁体   中英

Join with Or Condition

Is there a more efficient way to write this? I'm not sure this is the best way to implement this.

select * 
from stat.UniqueTeams uTeam
Left Join stat.Matches match 
on match.AwayTeam = uTeam.Id or match.HomeTeam = uTeam.id

OR in JOINS is a bad practice, because MSSQL can not use indexes in right way. Better way - use two selects with UNION:

SELECT * 
FROM stat.UniqueTeams uTeam
LEFT JOIN stat.Matches match 
ON match.AwayTeam = uTeam.Id

UNION

SELECT * 
FROM stat.UniqueTeams uTeam
LEFT JOIN stat.Matches match 
ON match.HomeTeam = uTeam.id

Things to be noted while using LEFT JOIN in query:

1) First of all, left join can introduce NULL(s) that can be a performance issue because NULL(s) are treated separately by server engine.

2) The table being join as null-able should not be bulky otherwise it will be costly to execute (performance + resource).

3) Try to include column(s) that has been already indexed. Otherwise, if you need to include such column(s) than better first you build some index(es) for them.

In your case you have two columns from the same table to be left joined to another table. So, in this case a good approach would be if you can have a single table with same column of required data as I have shown below:

; WITH Match AS 
(
-- Select all required columns and alise the key column(s) as shown below
    SELECT match1.*, match1.AwayTeam AS TeamId FROM stat.Matches match1 
    UNION
    SELECT match2.*, match2.HomeTeam AS TeamId FROM stat.Matches match2 
)
SELECT 
    *
FROM 
    stat.UniqueTeams uTeam
    OUTER APPLY Match WHERE Match.TeamId = uTeam.Id

I have used OUTER APPLY which is almost similar to LEFT OUTER JOIN but it is different during query execution. It works as Table-Valued Function that can preform better in your case.

my answer is not to the point, but i found this question seeking for "or" condition for inner join, so it maybe be useful for the next seeker we can use legacy syntax for case of inner join:

select * 
from stat.UniqueTeams uTeam, stat.Matches match 
where  match.AwayTeam = uTeam.Id or match.HomeTeam = uTeam.id

note - this query has bad perfomance (cross join at first, then filter). but it can work with lot of conditions, and suitable for dirty data research(for example t1.id=t2.id or t1.name=t2.name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM