2016-07-11 51 views
1

我的sql-fu並不強壯,而且我確信我錯過了一些簡單的嘗試讓它工作的東西。我有一個相當標準組表:Postgres:根據相關表中的條件獲取相關計數總數

users 
----- 
id 
name 


carts 
----- 
id 
user_id 
purchased_at 


line_items 
---------- 
id 
cart_id 
product_id 


products 
-------- 
id 
permalink 

我想購買車的總數爲每一個用戶,如果用戶已經購買了特定的產品。也就是說:如果至少有一個購買的購物車的某個固定產品帶有特定的固定鏈接,則無論其購物車的內容如何,​​我都會計算購買的購物車總數。

購物車的定義是當carts.purchased_at不爲空時。

select 
    u.id, 
    count(c2.*) as purchased_carts 

from users u 

inner join carts c on u.id = c.user_id 
inner join line_items li on c.id = li.cart_id 
inner join products p on p.id = li.product_id 
left join carts c2 on u.id = c2.user_id 

where 
    c.purchased_at is not NULL 
    and 
    c2.purchased_at is not NULL 
    and 
    p.permalink = 'product-name' 
group by 1 
order by 2 desc 

被出來爲purchased_carts的數字是奇怪的高,可能與乘以車的數目行項目的總數是多少?也許?我很難於看到結果。任何幫助將不勝感激。

回答

1

這應該幫助:

select u.id, 
     count(*) 
from users u join 
     carts c on c.user_id = u.id 
where c.purchased_at is not NULL and 
     exists (
     select null 
     from carts  c2 
     join line_items l on l.cart_id = c2.id 
     join products p on p.id  = l.product_id 
     where c2.user_id  = u.id and 
       c2.purchased_at is not NULL 
       p.permalink  = 'product-name') 
group by u.id 
order by count(*) desc; 

的存在謂詞是半聯接。

1

bool_or是你所需要的

select 
    u.id, 
    count(distinct c.id) as purchased_carts 
from 
    users u 
    inner join 
    carts c on u.id = c.user_id 
    inner join 
    line_items li on c.id = li.cart_id 
    inner join 
    products p on p.id = li.product_id 
where c.purchased_at is not NULL 
group by u.id 
having bool_or (p.permalink = 'product-name') 
order by 2 desc