如何强制加入左连接分支?

时间:2010-11-19 18:20:48

标签: sql mysql join left-join

我需要LEFT加入到整个t2 + t3分支,但是如果我能在t1和t2之间找到匹配的连接,我想强制执行t2和t3连接。

   SELECT T1.name,T2.bob,T3.a
     FROM T1
LEFT JOIN T2 ON t1.id = t2.t1_id
     JOIN T3 ON t2.id = T3.t2_id

语法是什么?

示例数据:

T1 [id,name]
1 aaa
2 bbb
3 ccc

T2 [id,t1_id,bob]
1,1,777
2,1,888
2,2,999

T3[id,t2_id,a]
1,2,'yeh'

预期结果:

 [name] , [a]   , [bob]
  aaa   , 'yeh' , 888
  bbb   , NULL  , NULL
  ccc   , NULL  , NULL

4 个答案:

答案 0 :(得分:4)

编辑:此查询会根据您的示例数据返回预期结果 - (另请注意,此查询是在Treefrog以下答案的帮助下完成的) -

SELECT t1.[name], t3.a, t2.bob
FROM T2 as t2
JOIN T3 as t3 ON t3.t2_id = t2.id
RIGHT JOIN T1 as t1 ON t1.id = t2.t1_id

我的老回答 -

SELECT a
FROM T1 as t1
INNER JOIN T2 as t2 ON t1.id = t2.t1_id
LEFT JOIN T3 as t3 ON t2.id = t3.t2_id

答案 1 :(得分:2)

SELECT T1.a
FROM T2
JOIN T3 ON T3.t2_id = T2.id
RIGHT JOIN T1 ON T1.id = T2.t1_id

答案 2 :(得分:0)

这两个都会给你你的结果。不确定哪个会表现得更好。

嵌套声明:

SELECT [name], NULL AS [a], NULL AS  [bob]
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.t1_id
LEFT OUTER JOIN t3 ON t2.id = t3.t2_id 
WHERE t3.t2_id IS NULL
AND (SELECT COUNT(*) FROM t1 AS t1b LEFT OUTER JOIN t2 AS t2b ON t1b.id = t2b.t1_id LEFT OUTER JOIN t3 AS t3b ON t2b.id = t3b.t2_id WHERE t1.id = t1b.id AND t3b.a IS NOT NULL) = 0
UNION
SELECT [name], [a], [bob]
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.t1_id
LEFT OUTER JOIN t3 ON t2.id = t3.t2_id 
WHERE t3.t2_id IS NOT NULL
ORDER BY t1.name

TEMPORARY TABLE:

CREATE TABLE #tmp_Rslt([name] varchar(50), [a] varchar(50), [bob] varchar(50))

--select matches
INSERT INTO #tmp_Rslt
SELECT [name], [a], [bob]
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.t1_id
LEFT OUTER JOIN t3 ON t2.id = t3.t2_id 
WHERE t3.t2_id IS NOT NULL
ORDER BY t1.name

--select t1's that didn't have matches
INSERT INTO #tmp_Rslt
SELECT [name], NULL AS [a], NULL AS  [bob]
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.t1_id
LEFT OUTER JOIN t3 ON t2.id = t3.t2_id 
WHERE t3.t2_id IS NULL
AND t1.[name] NOT IN (SELECT DISTINCT [name] FROM #tmp_Rslt)

SELECT *
FROM #tmp_Rslt

--cleanup.
DROP TABLE #tmp_Rslt

答案 3 :(得分:0)

这应该适用于MySQL

SELECT * FROM T1
LEFT JOIN (T2
 INNER JOIN T3 ON T2.id=T3.t2_id
) ON T1.id= T2.t1_id