内连接的内连接?

时间:2012-04-26 06:02:45

标签: sql db2

      **TableFruits**                        **TableNames**
   RecId    RId      FruitId       Price         RId  FruitId       Name
     1      A1        Null           3$           A1      1        Mango
     2      A2         2             4$           A2      2       Tomato

由于TableFruits中的FruitId下有Null,我想从TableNames中获取它,如

Select a.RecId,a.RId,b.FruitId from TableFruits a INNER JOIN TableNames b on a.RId=b.RId 
  1. 如何在此SQL语句中应用连接以包含表2中的FruitNames(我无法更改表的顺序)

2 个答案:

答案 0 :(得分:2)

Select a.RecId,a.RId,a.FruitId, b.Name
from TableFruits a 
LEFT OUTER JOIN TableNames b on a.RId=b.RId 

答案 1 :(得分:2)

SELECT a.RecId
     , a.RId
     , COALESCE(a.FruitId, b.FruitId) AS FruitId
     , b.Name
FROM TableFruits a 
  JOIN TableNames b 
    ON b.RId = a.RId  ;

由于RId中可能存在不匹配,因此需要外连接。 LEFTRIGHTFULL,具体取决于错配发生的方向。

MySQL没有FULL JOIN,所以你可以这样做:

SELECT a.RecId
     , a.RId
     , COALESCE(a.FruitId, b.FruitId) AS FruitId
     , b.Name
FROM TableFruits a 
  LEFT JOIN TableNames b 
    ON b.RId = a.RId 

UNION ALL

SELECT NULL
     , NULL
     , b.FruitId
     , b.Name
FROM TableFruits a 
  RIGHT JOIN TableNames b 
    ON b.RId = a.RId 
WHERE a.RId IS NULL  ;