通过多个值在表内进行自连接。 SQL、Postgresql

问题描述 投票:0回答:2

请帮助在一张表中通过不同字段进行自连接。给定表“项目”:

使用 PostgreSQL。

我需要从该表中获取所有值,其中

factId = 'urn:fact:drug:170'
factId1 ='urn:fact:drug:171'
以及
factId1.value ='false'
arrayIndexes
是相同的。

这意味着

factId
170 和 171 使用相同的
arrayIndex
具有一对一的关系。

因此需要

factId 'urn:fact:drug:170'
的所有值,其中有相同的
arrayIndex
factId 'urn:fact:drug:171'
相关,其值
'false'

这里是表中的 Item 列,这意味着对于每个 Item,我们都有自己的一组值 170 和 171。 谢谢你。

我尝试过这个,但我不确定这是否有效且快速:

SELECT l.value
FROM Items l
INNER JOIN Items p on p.item  = l.item
INNER JOIN Items c on c.item  = l.item
WHERE l.factid  = 'urn:fact:drug:170' AND c.factid = 'urn:fact:drug:170'  
AND p.factid  = 'urn:fact:drug:171' AND p.value='false' 
AND p.arrayindex = l.arrayindex

下班后有很多重复的事情。 请检查我的询问。

sql postgresql inner-join self-join sequel
2个回答
0
投票

您的查询可以是:

with t as (
  select distinct arrayindex
  from items
  where factid = 'urn:drug:171' and value = 'false'
)
select * from items
where arrayindex in (select * from t)
  and (factid = 'urn:drug:170' or factid = 'urn:drug:171') -- optional condition;

数据库小提琴

详情:

  1. t
    CTE 查询查找满足条件的所有行的唯一
    arrayindex

    where factid = 'urn:drug:171' and value = 'false'
    ;
  2. 外部查询查找所有带有
    factid = 'urn:drug:170'
    的行。结果行按我们从上一步收到的
    arrayindex
    值进行过滤。

0
投票

您明显的问题是源表中的重复项。

170
行在您的日期中出现了 3 次,
171
行出现了两次。

要获得一对一关系,您必须以某种方式引入唯一的标识 - 我使用

row_number

它是一个简单的连接,在行号上有额外的谓词

查询(样本数据为CTE)

with tab as (
select * from (values 
('urn:fact:drug:170', '88cafe', 15),
('urn:fact:drug:170', '88cafe', 15),
('urn:fact:drug:170', '88cafe', 15),
('urn:fact:drug:171', 'false', 15),
('urn:fact:drug:171', 'false', 15)
)
t (factId,value,arrayIndexes)
),
-- from here your query --
t170 as (
select tab.*,
row_number() over (order by value) as rn
from tab
where factId = 'urn:fact:drug:170'
),
t171 as (
select tab.*,
row_number() over (order by value) as rn
from tab
where factId = 'urn:fact:drug:171' and value ='false'
)
select 
 t170.factid, t170.value, t170.arrayIndexes,
 t171.factid factid2c
from t170
join t171 on t170.arrayIndexes = t171.arrayIndexes and
t170.rn = t171.rn;

结果

factid           |value |arrayindexes|factid2c         |
-----------------+------+------------+-----------------+
urn:fact:drug:170|88cafe|          15|urn:fact:drug:171|
urn:fact:drug:170|88cafe|          15|urn:fact:drug:171|

因此您可以连接两行,第三行将被跳过,因为两边都没有匹配项

© www.soinside.com 2019 - 2024. All rights reserved.