查询可能在同一类别上与之交互的用户

ftf50wuq  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(250)

我需要做一个查询,列出所有的用户,可能会相互作用,在同一个类别与注解。基本上,每个在某个类别上做了注解的人,特定用户都在该类别上做了注解。怎么办?
假设用户id为3,留下了一个注解(注解10):

ID  U   CATEGORY  NOTE
1   3   5         'note_10'
2   1   3         'note_11'
3   2   5         'note_12'
4   5   2         'note_13'
5   6   5         'note_14'
6   7   5         'note_15'

预期结果:

U
2
6
7

身份证号码2、6和7在同一类别上发布。

5q4ezhmt

5q4ezhmt1#

我想你想要一个带有过滤功能的自连接:

select t.*
from t join
     t tt
     on tt.category = t.category and
        tt.note = 'note_10';

这是一把小提琴。
如果要筛选出原始用户,可以使用:

from t join
     t tt
     on tt.category = t.category and
        tt.note = 'note_10' and
        tt.id <> t.id;
bvjxkvbb

bvjxkvbb2#

我想你想要 exists :

select t.u
from mytable t
where 
    t.u <> 3
    and exists (select 1 from mytable t1 where t1.u = 3 and t1.category= t.category)

这将为您提供在任何类别用户3上发布的所有用户。
这可能会在一个给定的用户中生成重复项,该用户有几个与用户相同的类别 3 -如果你想避免这种情况,你可以使用 select distinct 相反。
另一个选项是窗口功能:

select u
from (
    select u, count(*) filter(where u = 3) over(partition by category) cnt
    from mytable
) t
where u <> 3 and cnt > 0

相关问题