我在数据库中有3个相关的表,表是A,B& C 表结构如下
表A
id | name_A
--- + ---------
1 | Endru
2 | maz
3 | Hudson
表B
id | name_B
----- + -------
10 | Food
11 | clothes
表C
id | status
--- + -------
1 | exist
10 | exist
3 | none
我想生产这样的
id | name_A | name_B | status
------------------------------------------
1 | Endru | null | exist
10 | null | food | exist
3 | hudson | null | none
我如何实现,我尝试过使用内部和外部连接,但没有成功。
感谢
答案 0 :(得分:0)
您可以使用union all
和聚合:
select id, max(name_a) as name_a, max(name_b) as name_b,
coalesce(max(status), 'none') as status
from (select id, name_a, NULL as name_b, NULL as status
from tableA
union all
select id, NULL, name_b, NULL
from tableB
union all
select id, NULL, NULL as name_b, status
from tableC
) abc
group by id;
答案 1 :(得分:0)
尝试此查询:
SELECT `id`, `name_A`, `name_B`, `status`
FROM `tableC`
LEFT JOIN `tableA` USING (`id`)
LEFT JOIN `tableB` USING (`id`)
答案 2 :(得分:0)
我认为以下查询将获取您需要的内容
SELECT tableC.id, TableA.name_A,TableB.name_B,tableC.status
FROM tableC
LEFT JOIN TableA on TableC.id = TableA .id
LEFT JOIN TableB on TableC.id = TableB .id
答案 3 :(得分:0)
使用此查询:
SELECT tbc.Id,tba.Name_A,tbb.NameB,tbc.[Status]
FROM tablec tbc
INNER JOIN tablea tba on tba.Id = tbc.Id
INNER JOIN tableb tbb on tbb.Id = tbc.Id