小编Mar*_*cin的帖子

array_agg 包含另一个 array_agg

t1
id|entity_type
9|3
9|4
9|5
2|3
2|5
           
t2  
id|entity_type
1|3
1|4
1|5     
Run Code Online (Sandbox Code Playgroud)
SELECT t1.id, array_agg(t1.entity_type)
    FROM t1
GROUP BY
    t1.id
HAVING ARRAY_AGG(t1.entity_type ORDER BY t1.entity_type) = 
    (SELECT ARRAY_AGG(t2.entity_type ORDER BY t2.entity_type) 
        FROM t2
    WHERE t2.id = 1
    GROUP BY t2.id);
Run Code Online (Sandbox Code Playgroud)

结果:

t1.id = 9|array_agg{3,4,5}      
    
Run Code Online (Sandbox Code Playgroud)

我有两张桌子t1t2。我想获取t1.id数组t1.entity_type等于t2.entity_type数组的值。

在这种情况下一切正常。因为t2.id = 1我收到了t1.id = 9。两者都有相同的数组entity_type{3,4,5}

现在我不仅想要获得t1.id相等的集合,还想要获得较小的集合。如果我t2这样修改:

t2  
id|entity_type
1|3
1|4
Run Code Online (Sandbox Code Playgroud)

并以这种方式修改查询:

SELECT t1.id, array_agg(t1.entity_type) …
Run Code Online (Sandbox Code Playgroud)

sql arrays postgresql relational-division

3
推荐指数
1
解决办法
1994
查看次数

标签 统计

arrays ×1

postgresql ×1

relational-division ×1

sql ×1