0
      **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(我无法更改表的顺序)
4

2 回答 2

2
Select a.RecId,a.RId,a.FruitId, b.Name
from TableFruits a 
LEFT OUTER JOIN TableNames b on a.RId=b.RId 
于 2012-04-26T06:04:47.183 回答
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,因此您需要一个外连接。LEFT,RIGHTFULL, 取决于可能发生不匹配的一侧。

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  ;
于 2012-04-26T06:20:01.840 回答