表之间的外连接

时间:2015-10-05 11:54:39

标签: sql-server join

有一个表table1,其中包含hId列。这也可以包含数字,包括0null。在某些加入关系后,每个table1.hId都有一个full name,但仅限于hId !=0 or null

然后table2.Hpid = table1.hId -- but only if hId is not null or != 0

在此之后,table2.exId = table3.Id,最后是table3.lId = table4.Id

我尝试了什么

SELECT
  (SELECT table4.fullName
   FROM table4
   WHERE table4.Id = table3.lId)
FROM table1
JOIN table2 ON table1.hId = table2.hpId
JOIN table3 ON table3.Id = table2.exId

但是这样我只得到table1.id = table2.hId的行。我相信我必须使用case语句(当table.hId = 0 or null =>时打印错误'),但我怎样才能实现此目标?

2 个答案:

答案 0 :(得分:1)

我无法理解目标,但尝试使用左连接:

SELECT ISNULL(table4.Id, 'ERROR') AS Table4Id
       , table4.fullName
FROM table1
LEFT JOIN table2 ON table1.holidayparkid2 = table2.Id
LEFT JOIN table3 ON ed.Id = table2.exId <-- what's ed.Id?
LEFT JOIN table3 ON table4.Id = table3.lId;

答案 1 :(得分:0)

SELECT CASE WHEN (table.hId = 0 OR table.hId IS NULL) THEN 'ERROR'
            ELESE table4.fullName
       END AS fullName
FROM table1
JOIN table2 ON table1.holidayparkid2 = table2.Id
JOIN table3 ON ed.Id = table2.exId
JOIN table4 ON table4.Id = table3.lId
--WHERE table1.hId!=0 AND table1.hId IS NOT NULL  --not need with case