如何仅从具有PostgreSQL内部联接中不存在的ID的表中选择行?
我有下表如何仅从具有PostgreSQL内部联接中不存在的ID的表中选择行?,sql,postgresql,inner-join,Sql,Postgresql,Inner Join,我有下表 postgres=# select * from joins_example; user_id | price | id | email ---------+--------+----+-------------------------- 1 | $30.00 | | 5 | $50.00 | | 7 | $20.00 | | | | 1 |
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)
用户id和id之间的自内部联接产生
我想要的是:
user_id | price | id | email | user_id | price | id | email
---------+--------+----+-------------------+---------+--------+----+--------------------------
7 | $50.00 | | | | | |
| | | | | | 2 | fahir@example.com
或:
甚至
这将是一个良好的开端
具体地说,我想知道如何仅从joins_示例中选择具有用户ID或内部join中不存在的ID的行
SELECT *
FROM joins_example AS w
LEFT JOIN (
select x.user_id
from joins_example as x
inner join joins_example as y on x.user_id = y.id
) AS z ON z.user_id = w.user_id or z.user_id = w.id
WHERE z.user_id IS NULL;
这是一个足够好的开始
user_id | price | id | email | user_id
---------+--------+----+-------------------+---------
7 | $20.00 | | |
| | 2 | fahir@example.com |
可以考虑使用不存在条件的相关子查询的方法:
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
)
)
:
挑选*
来自示例j
其中,j.user_id为NULL,j.id为NULL
或j.user\u id不为NULL且不存在从连接示例j2中选择1,其中j2.id=j.user\u id
或者j.id不为NULL且不存在从连接示例j2中选择1,其中j2.user\u id=j.id;
假设用户id和id在一行中相等(如果两者都设置了),安全吗?为什么您想要上面两个输出中的一个而不是最后一个?没有额外的信息,您只需要更多的检查来确定您的值在哪里。额外的信息是,如果它是作为联接的一部分生成的,它将来自交叉积的哪一侧。这超出了问题的范围,但我希望将其与内部联接结合起来。完全联接包含内部联接以及两边都为空的交叉行。这对于引用不同表的联接是可以的,但对于自联接,它会创建许多行,这些行包含与匹配搜索条件的行相同的信息。我需要一种快速、直观和无损耗的方法来在高度异构的数据上进行自连接。您还可以在最后的输出中找到辅助信息。您只需要查找两个连接字段中的哪一个是空的。现在我只需要将这些信息编码为可以与内部联接合并的格式。现在我知道你是对的,没有额外的信息,因为在叉积中,两边都会出现。这意味着其余的列可以是空的。
SELECT *
FROM joins_example AS w
LEFT JOIN (
select x.user_id
from joins_example as x
inner join joins_example as y on x.user_id = y.id
) AS z ON z.user_id = w.user_id or z.user_id = w.id
WHERE z.user_id IS NULL;
user_id | price | id | email | user_id
---------+--------+----+-------------------+---------
7 | $20.00 | | |
| | 2 | fahir@example.com |
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
)
)
| user_id | price | id | email |
| ------- | ----- | --- | ----------------- |
| 7 | 20.00 | | |
| | | 2 | fahir@example.com |