我无法弄清楚我需要在这里执行的是Join语句还是Union。
宠物
Id name color
1 wiskers grey
2 midnight black
3 ralph yellow
4 Bob brown
拍摄表
Id Rabbies a123
2 Yes No
4 No No
笔记表
Id Notes
4 This pet is blind
2 This pet has no owner
搜索结果:
Id Name Color Rabbies A123 Notes
1 Wiskers grey Null Null Null
2 midnight black Yes No This pet has no owner
......
答案 0 :(得分:2)
我认为您想要left join
:
select p.*, s.rabies, s.a123, n.notes
from pets p left join
shots s
on s.id = p.id left join
notes n
on n.id = p.id;
答案 1 :(得分:0)
联接和联合都用于合并数据,并且都可以在此处使用。但是,我建议使用联接,联接合并来自不同表的列,这似乎是您想要包含的内容。您希望将所有列都包含在一行中(用于动物的ID)。
https://www.codeproject.com/Articles/1068500/What-Is-the-Difference-Between-a-Join-and-a-UNION
尝试该链接以获取更多信息。
答案 2 :(得分:0)
如果是这种情况
create table Shots (id serial primary key, Rabbies varchar, a123 varchar, pet_id int);
insert into shots (pet_id, Rabbies, a123) values (2, 'Yes','No'), (4, 'No','No');
create table notes (id serial primary key, notes varchar, pet_id int);
insert into notes (pet_id, notes) values (4, 'This pet is blind'), (2, 'This pet has no owner');
select p.id, p.name, p.color, s.rabbies, s.a123, n.notes
from pets p
left join shots s on p.id = s.id
left join notes n on p.id = n.id;