**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
答案 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
中可能存在不匹配,因此需要外连接。 LEFT
,RIGHT
或FULL
,具体取决于错配发生的方向。
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 ;