我的sql-fu并不强大,而且我确定我在尝试使其工作时遗漏了一些简单的东西。我有一套相当标准的表格:
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
buy_carts的数字奇怪地高,可能与订单项总数乘以购物车数量有关?也许?我对这个结果感到非常难过。任何帮助将不胜感激。
答案 0 :(得分: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 :(得分:1)
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