gpt4 book ai didi

sql - PostgreSQL 条件连接

转载 作者:太空狗 更新时间:2023-10-30 01:44:37 26 4
gpt4 key购买 nike

假设我有以下表格 --

smallville=# create table contacts (name varchar(16), address_id int); 
CREATE TABLE
smallville=# create table addresses (address_id int, address varchar(16));
CREATE TABLE
smallville=# create table partners (name1 varchar(16), name2 varchar(16));
CREATE TABLE

smallville=# insert into contacts values ('Clark Kent', NULL), ('Loise Lane', 1);
INSERT 0 2
smallville=# insert into addresses values (1, 'Manhattan'), (2, 'North Pole');
INSERT 0 2
smallville=# insert into partners values ('Clark Kent', 'Loise Lane'),
('Loise Lane', 'Clark Kent') ;
INSERT 0 2

我可以得到姓名和地址 --

smallville=# select c.name, a.address from contacts c
left outer join addresses a
on c.address_id = a.address_id ;
name | address
------------+-----------
Clark Kent | (NULL)
Loise Lane | Manhattan
(2 rows)

但是我如何获得以下信息,即如果某人的地址丢失,则显示他/她伴侣的地址? --

    name    |  address  
------------+-----------
Clark Kent | Manhattan
Loise Lane | Manhattan
(2 rows)

谢谢。

最佳答案

select c.name, coalesce(a.address, a1. address) from contacts c
left outer join addresses a on c.address_id = a.address_id
left outer join partners on c.name=partners.name1
left outer join contacts c1 on c1.name=partners.name2
left outer join addresses a1 on c1.address_id = a1.address_id;

关于sql - PostgreSQL 条件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6168359/

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