gpt4 book ai didi

sql - 如何仅从表中选择具有不存在于 PostgreSQL 内部联接中的 ID 的行?

转载 作者:行者123 更新时间:2023-11-29 12:23:17 25 4
gpt4 key购买 nike

我有下表

postgres=# select * from joins_example;
user_id | price | id | email
---------+--------+----+--------------------------
1 | $30.00 | |
5 | $50.00 | |
7 | $20.00 | |
| | 1 | hadil@example.com
| | 5 | saiid@example.com
| | 2 | fahir@example.com
6 | $60.00 | 6 | oma@example.com
8 | $40.00 | 8 | nasim@example.com
| | 8 | nasim.hassan@example.com
9 | $40.00 | 9 | farah@example.com
9 | $70.00 | |
10 | $80.00 | | majid@example.com
| | 10 | majid.seif@example.com
(13 rows)

user_idid 之间的自内连接产生

postgres=# select * from joins_example as x inner join joins_example as y on x.user_id = y.id;
user_id | price | id | email | user_id | price | id | email
---------+--------+----+-------------------+---------+--------+----+--------------------------
1 | $30.00 | | | | | 1 | hadil@example.com
5 | $50.00 | | | | | 5 | saiid@example.com
6 | $60.00 | 6 | oma@example.com | 6 | $60.00 | 6 | oma@example.com
8 | $40.00 | 8 | nasim@example.com | | | 8 | nasim.hassan@example.com
8 | $40.00 | 8 | nasim@example.com | 8 | $40.00 | 8 | nasim@example.com
9 | $40.00 | 9 | farah@example.com | 9 | $40.00 | 9 | farah@example.com
9 | $70.00 | | | 9 | $40.00 | 9 | farah@example.com
10 | $80.00 | | majid@example.com | | | 10 | majid.seif@example.com
(8 rows)

我想要的是:

 user_id | price  | id |       email       | user_id | price  | id |          email           
---------+--------+----+-------------------+---------+--------+----+--------------------------
7 | $50.00 | | | | | |
| | | | | | 2 | fahir@example.com

或:

 user_id | price  | id |       email       | user_id | price  | id |          email           
---------+--------+----+-------------------+---------+--------+----+--------------------------
| | | | 7 | $50.00 | |
| | 2 | fahir@example.com | | | |

甚至

 user_id | price  | id |          email           
---------+--------+----+--------------------------
5 | $50.00 | |
| | 2 | fahir@example.com

将是一个好的开始。

具体来说,我想知道如何仅从 joins_example 中选择具有 user_idid 的行内连接。

最佳答案

您可以考虑使用具有NOT EXISTS 条件的相关子查询的方法:

select * 
from joins_example as x
where
(
x.user_id is not null
and not exists (
select 1 from joins_example y where x.user_id = y.id
)
)
or (
x.id is not null
and not exists (
select 1 from joins_example y where x.id = y.user_id
)
)

Demo on DB Fiddle :

| user_id | price | id  | email             |
| ------- | ----- | --- | ----------------- |
| 7 | 20.00 | | |
| | | 2 | fahir@example.com |

关于sql - 如何仅从表中选择具有不存在于 PostgreSQL 内部联接中的 ID 的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58151218/

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