I have a query with 4 tables. It needs to return the value from the fourth table by joining the first table to either the second or the third table depending on if the join is on the second returned a match.

Here's what I tried after looking this up online:

SELECT t1.field1, t4.field1   
FROM t1
LEFT JOIN t2 ON t1.field1 = t2.field1
LEFT JOIN t3 ON t1.field1 = t3.field1   
LEFT JOIN t4 ON COALESCE(t2.field1, t3.field1)

Right now, it only returns a value from the fourth table when a match is made from the join between t1 and t2.

Is there anyway to achieve this? Thanks in advance for your suggestions

有帮助吗?

解决方案

Well, apart from what I think was an error on the copye/paste (it's missing part of the last join condition), your query should work:

SELECT t1.field1, t4.field1
FROM t1
LEFT JOIN t2 
    ON t1.field1 = t2.field1
LEFT JOIN t3 
    ON t1.field1 = t3.field1
LEFT JOIN t4 
    ON COALESCE(t2.field1, t3.field1) = t4.field1

其他提示

Seems like your query should work as is (aside from missing expression as Lamak mentioned), alternatively:

SELECT sub.field1, t4.field1
FROM (SELECT t1.field1, COALESCE(t2.field1, t3.field1) as field2
      FROM t1
      LEFT JOIN t2 
         ON t1.field1 = t2.field1
      LEFT JOIN t3 
         ON t1.field1 = t3.field1
     )sub
LEFT JOIN t4
  ON sub.field2 = t4.field1
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top