I have two table a and b
表a
ID
a
b
c
表b
ID Value
a 1
b 2
default 0
所以我想在完全匹配时在ID上连接两个表,否则使用默认值 期望的结果
ID Value
a 1
b 2
c 0
答案 0 :(得分:0)
为此目的使用LEFT OUTER JOIN
,如
select t1.ID, COALESCE(t2.Value, 0) as Value
from tablea t1
left join tableb t2 on t1.ID = t2.ID;
答案 1 :(得分:0)
试试这个:
SELECT a.ID, b.Value
FROM a
INNER JOIN b
ON a.ID = b.ID
UNION ALL
SELECT a.ID, b.Value
FROM a
CROSS JOIN b
WHERE
a.id <> b.id
这将为您提供所有匹配的ID,然后CROSS JOIN查询的UNION应该为不匹配的ID提供默认值。
答案 2 :(得分:0)
试试这个:
SELECT t1.ID,
COALESCE(t2.Value, (SELECT Value FROM tableb t3 WHERE ID ='default')) AS Value
FROM tablea t1
LEFT JOIN tableb t2 on t1.ID = t2.ID;