gpt4 book ai didi

sql - 将两个或多个表关联在一起时,如何在查询中获取具有空值的行?

转载 作者:行者123 更新时间:2023-12-04 04:13:06 24 4
gpt4 key购买 nike

drop table person;
drop table interest;
drop table relation;


create table person (
pid int primary key,
fname varchar2(20),
age int,
interest int references interest(intID),
relation int references relation(relID)
);

create table interest (
intID int primary key,
intName VARCHAR2(20)
);

create table relation (
relID int primary key,
relName varchar2(20)
);

insert into person values(1, 'Rahul', 18, null, 1);
insert into person values(2, 'Sanjay', 19, 2, null);
insert into person values(3, 'Ramesh', 20, 4, 5);
insert into person values(4, 'Ajay', 17, 3, 4);
insert into person values(5, 'Edward', 18, 1, 2);

insert into interest values(1, 'Cricket');
insert into interest values(2, 'Football');
insert into interest values(3, 'Food');
insert into interest values(4, 'Books');
insert into interest values(5, 'PCGames');

insert into relation values(1, 'Friend');
insert into relation values(2, 'Friend');
insert into relation values(3, 'Sister');
insert into relation values(4, 'Mom');
insert into relation values(5, 'Dad');

select * from person;
select * from interest;
select * from relation;

以上代码以代码形式显示了表格及其架构。以下是我编写的查询。

select person.fname, interest.intName, relation.relName
from person, interest, relation
where person.interest = interest.intID and relation.relID = person.relation;

This is the output I am getting. (Img1)

Instead of output I am getting, this is the output I need. (Img2)

img2 是我写的,在我的查询中(如在 img1 中)空值被忽略。

为什么会这样?请提供解决方案。谢谢。

最佳答案

看起来您需要的是外连接。

SQL> select p.fname, i.intname, r.relname
2 from person p left join interest i on p.interest = i.intid
3 left join relation r on r.relid = p.relation;

FNAME INTNAME RELNAME
-------------------- -------------------- --------------------
Rahul Friend
Edward Cricket Friend
Ajay Food Mom
Ramesh Books Dad
Sanjay Football

SQL>

关于sql - 将两个或多个表关联在一起时,如何在查询中获取具有空值的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61372224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com