态度是多对多的。我的参与。 PostgreSQL的

时间:2019-07-05 18:24:50

标签: sql postgresql

我有三个表 t_items t_users items_likes

create table t_items (
item_id varchar PRIMARY KEY,
title varchar);

create table t_users(
user_id varchar PRIMARY KEY,
title varchar);

CREATE TABLE items_likes (
like_id varchar PRIMARY KEY,
item_id varchar references t_items(item_id),
user_id varchar references t_users(user_id));

insert into t_items values('it1', 'item1');
insert into t_items values('it2', 'item2');
insert into t_items values('it3', 'item3');
insert into t_items values('it4', 'item4');
insert into t_items values('it5', 'item5');
insert into t_items values('it6', 'item6');
insert into t_items values('it7', 'item7');
insert into t_items values('it8', 'item8');
insert into t_items values('it9', 'item9');
insert into t_items values('it0', 'item0');

insert into t_users values('user1', 'name1');
insert into t_users values('user2', 'name2');
insert into t_users values('user3', 'name3');
insert into t_users values('user4', 'name4');
insert into t_users values('user5', 'name5');

insert into items_likes values('li1', 'it1', 'user1');
insert into items_likes values('li2', 'it2', 'user1');
insert into items_likes values('li3', 'it2', 'user2');
insert into items_likes values('li4', 'it3', 'user2');
insert into items_likes values('li5', 'it3', 'user3');
insert into items_likes values('li6', 'it1', 'user3');
insert into items_likes values('li7', 'it4', 'user4');
insert into items_likes values('li8', 'it2', 'user4');
insert into items_likes values('li9', 'it5', 'user5');
insert into items_likes values('li0', 'it1', 'user5');

我需要一个请求,该请求将向用户显示喜欢的总数。 在这里,这样的请求仅给出了我的喜欢次数。我需要喜欢的总数。

select
    t_items.item_id,
    t_items.title,
  count(distinct items_likes.like_id) as likes_count
from t_items
LEFT OUTER join items_likes on t_items.item_id = items_likes.item_id and items_likes.user_id = 'user3'
where 
items_likes.user_id = 'user3'
group by t_items.item_id, items_likes.user_id;

我有错误的结果:

  item_id title likes_count
1  it1    item1     1
2  it3    item3     1

我需要结果:

  item_id title likes_count
1  it1    item1     3
2  it3    item3     2

如何找出我参加的喜欢总数?

工作示例: https://rextester.com/live/TZUAAE31639

2 个答案:

答案 0 :(得分:1)

这可以使用window function来完成:

demo:db<>fiddle

SELECT
    item_id,
    count
FROM (
    SELECT
        il.item_id,
        i.title,
        user_id,
        COUNT(*) OVER (PARTITION BY il.item_id)
    FROM
        items_likes il
    JOIN t_items i ON i.item_id = il.item_id
) s
WHERE user_id = 'user3'

分区将项目聚类,并对每个组进行计数。此计数将作为单独的列添加到原始表中。

添加组计数后,用户可以过滤该表。

答案 1 :(得分:1)

select
    t_items.item_id,
    min(t_items.title) as title,
    count(case when item_likes.user_id = 'user3' then 1 else null end) as my_likes
    count(distinct items_likes.like_id) as total_likes
from t_items left outer join items_likes on t_items.item_id = items_likes.item_id
group by t_items.item_id, items_likes.user_id
having count(case when item_likes.user_id = 'user3' then 1 else null end) > 0;