PostgreSQL-三个表。两个连接。不相关的结果

时间:2019-01-10 17:04:49

标签: sql postgresql

我有三个表 t_items market items_likes

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

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

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

最后,我想得到一个包含点赞市场数量的结果。

select
  t_items.item_id,
  t_items.title,
  count(items_likes.item_id) as likes_count,  
  count(market.item_id) as market_count
from market
inner join t_items on market.item_id = t_items.item_id
inner join items_likes on t_items.item_id = items_likes.item_id
group by t_items.item_id;

但是,当我向请求中添加顶赞的数量时,我失去了 markets 数量的结果。

这是一个有效的示例: https://rextester.com/live/HVUGW7783

如何根据喜欢和存储的确切数量发出请求?

谢谢。

2 个答案:

答案 0 :(得分:1)

加入2条查询,第1条获得喜欢的次数,第2条获得市场的人数:

select t_items.item_id, t_items.title, t.likecounter, t.marketcounter from (
  select t.item_id, t.likecounter, tt.marketcounter from (
    select t_items.item_id, count(items_likes.like_id) likecounter
    from t_items inner join items_likes
    on items_likes.item_id = t_items.item_id
    group by t_items.item_id
  ) t inner join (
    select t_items.item_id, count(market.item_id) marketcounter 
    from t_items inner join market 
    on market.item_id = t_items.item_id 
    group by t_items.item_id
  ) tt
  on tt.item_id = t.item_id
) t inner join t_items
on t_items.item_id = t.item_id
order by t_items.item_id

请参见demo

答案 1 :(得分:1)

您可以按项目进行汇总并计算不同市场的数量,并希望以双打消除问题,而在三张表中加入双打则可能会导致双打,例如:

select
  t_items.item_id,
  t_items.title,
  count(distinct items_likes.like_id) as likes_count,  
  count(distinct market.market_id ) as market_count
from market
left join t_items on market.item_id = t_items.item_id
left join items_likes on t_items.item_id = items_likes.item_id
group by t_items.item_id
order by t_items.title;

左连接很重要,因此您仍将为具有例如3个市场,但0个赞。通过内部联接,您将只会获得具有至少一个市场和至少一个类似市场的商品。