我有两张表格如下
TableA
A_id name
---- ----
123 Test1
124 Test2
125 Test3
126 Test4
TableB
B_id fk_A_id value type_id
---- ------- ----- -------
1 123 op1 1
2 123 hello 2
3 123 abc 3
4 126 op2 1
5 126 hello 2
6 126 def 3
我使用查询加入两个表
select TableA.A_id as id, TableA.name as name, TBL2.type_name as type_name
from TableA
full join (
select fk_A_id, value as type_name
from TableB
where type_id = 2
)TBL2 on TableA.A_id = TBL2.fk_A_id
返回结果将是
id name type_name
-- ---- ---------
123 Test1 hello
124 Test2
125 Test3
126 Test4 hello
我的问题是如何用“你好”填充空列。同样是TableB的返回结果,type_id =' 2'将在TableB上有类似的字符串
答案 0 :(得分:0)
我想你想要left join
,就像这样:
select a.A_id as id, a.name as name, b.type_name as type_name
from TableA a left join
TableB b
on a.A_id = b.fk_A_id and b.type_id = 2;
不需要子查询,full join
过度杀伤。
如果您希望NULL
值也为hello
,请使用coalesce()
:
select a.A_id as id, a.name as name,
coalesce(b.type_name, 'hello') as type_name
from TableA a left join
TableB b
on a.A_id = b.fk_A_id and b.type_id = 2;