我有一个问题,我没有找到答案。
这里有一个例子:
表:兴趣
- id:整数 - 主键
- 名称:兴趣名称 - 唯一
- 人气:兴趣人气
表:用户
- id:整数 - 主键
- 电子邮件:字符串 - 唯一
- 兴趣:整数数组 - “兴趣”表的外键
我希望通过 'users' 表计算 'interests' 表的 'popularity' 列。
表用户
id | email | interests
0 | toto0.gmail.com | [ 0 ]
1 | toto1.gmail.com | [ 0, 1 ]
2 | toto2.gmail.com | [ 1 ]
3 | toto2.gmail.com | [ 2 ]
表兴趣
id | name | popularity
0 | 'interest 0' | 2
1 | 'interest 1' | 2
2 | 'interest 2' | 1
3 | 'interest 3' | 0
我试过这个:
UPDATE interests SET popularity = (SELECT COUNT(*) from public.users where ARRAY[interests] @> ARRAY[interests.id]);
但我不想运行查询来更新兴趣表。我的意思是,我希望在用户订阅时自动填充“人气”列。
如果我创建这样的“视图”,它应该可以按我的意愿工作吗?
CREATE VIEW interests_popularity (id, popularity) AS
SELECT COUNT(1) as popularity, interest.id
FROM public.user, interest
WHERE ARRAY[public.user.interests] @> ARRAY[interest.id]
GROUP BY interest.id;
有没有更有效的方法来做到这一点?