I have three tables:
sales, which are purchases from a storeitems, which are all the items the store carriessale_items, which associatesalesto theitemsbought in that sale. So a row insale_itemshas both asale_idand anitem_id.
What is the most efficient way to find all sales that include a sale_item corresponding to a given item?
My first guess was
select sale_id, item_id, count(*)
from sales as s
join sale_items as si on si.sale_id=s.id
group by item_id
order by count(*) desc
But then if a given sale had multiple sale_items with the same item, that sale is counted multiple times. That’s not what I want–I only want to count the sales themselves.
What is the best way to do this?
Sounds like you want to find the number of sales that included a specific item: