开发者

SQL Join on first matched field

开发者 https://www.devze.com 2023-02-16 09:45 出处:网络
I have a query to join 2 tables in the following way. Table1 has a field (LinkTo) that may (or may not) appear in one of three fields in tabl开发者_开发百科e Table2 (Link, Link1, Link2).I need try jo

I have a query to join 2 tables in the following way.

Table1 has a field (LinkTo) that may (or may not) appear in one of three fields in tabl开发者_开发百科e Table2 (Link, Link1, Link2). I need try joining LinkTo to Link, then Link1 then Link2. As soon as I match on one (say Link1) I should stop trying to join.

Thanks

Mark


This might be what you are looking for. It joins in the order of fields you mentioned (edited to answer a question from the comments):

SELECT t1.*, t2.*,
    CASE WHEN (t1.LINKTO = t2.LINK) THEN 'LinkedWithLink' 
         WHEN (t1.LINKTO <> t2.LINK 
           AND t1.LINKTO = t2.LINK1) THEN 'LinkedWithLink1' 
         WHEN (t1.LINKTO <> t2.LINK1 
           AND t1.LINKTO <> t2.LINK1 
           AND t1.LINKTO = t2.LINK2) THEN 'LinkedWithLink2' END AS chosen_join
FROM TABLE1 t1 
[LEFT OUTER] JOIN TABLE2 t2
ON (t1.LINKTO = t2.LINK OR 
   (t1.LINKTO <> t2.LINK AND t1.LINKTO = t2.LINK1) OR
   (t1.LINKTO <> t2.LINK1 AND t1.LINKTO <> t2.LINK1 AND t1.LINKTO = t2.LINK2)

Note, I don't know whether you need a LEFT OUTER join or not... In any case, you should be aware of a potentially very slow execution plan with this...


SELECT * 
FROM TABLE1 t1
  JOIN TABLE2 t2 ON (t1.LINKTO = t2.LINK OR 
                     t1.LINKTO = t2.LINK1 OR
                     t1.LINKTO = t2.LINK2)

As soon as one of statements is true other does not checks

0

精彩评论

暂无评论...
验证码 换一张
取 消