3

我有 2 张桌子,看起来像:

Table A
key1 key2 key3
1    a    a
2    a    a
3    a    a

Table B
key1 key2 key3
1    xxx  zzz
2    yyy  www

现在我想在 A 和 B 中有一个大表,其中 A.key1 匹配 B.key1 粘贴 B 的内容,否则如果没有 key1 匹配粘贴默认值

例如

Key1 Key2 Key3 Key5 Key6
1    a    a    xxx  zzz            
2    a    a    yyy  www               
3    a    a    0    0       

什么是查询?

4

3 回答 3

3

你需要左连接:

select
  a.key1,
  a.key2,
  a.key3,
  ifnull(b.key2, 0) as key4,
  ifnull(b.key3, 3) as key5
from
  tableA a
left join
  tableB b on b.key1=a.key1
于 2012-04-26T19:59:11.897 回答
2
select * from a left outer join b on a.key1 = b.key1

(这将为没有来自 b 的匹配行的 b 列提供空值)

于 2012-04-26T19:59:03.550 回答
1
select key1, key2, key3, 
    case key5 when null then default(key5) else key5 as key5,  
    case key6 when null then default(key6) else key6 as key6
from a
left outer join b on a.key1 = b.key1

编辑

SQLFiddle 示例

select a.key1, a.key2, a.key3, 
       ifnull(b.key2, 0) as key5,  
       ifnull(b.key2, 3) as key6
from a
left outer join b on a.key1 = b.key1
于 2012-04-26T20:02:16.773 回答