简体   繁体   中英

Getting count of rows from one table where at least one related item from another table matches criteria

I have 'products' table and related 'variations' table, one product can have one or more variations. 'variations' table has 'status' column, its value can be 0 or 1. I want to get the number of products (COUNT()) which have at least one variation of status 1. How to make a query that would do that? [EDIT] Ok, I thought that if I simplify the question I will get away with the table structure, but, here we go (only columns relevant to the question and some mock data):

It's actually 3 linked tables: table 1: 'products'

id name
1 t-shirt
2 shoes
3 shorts

table 2: variations

id product_id
1 1
2 1
3 2
4 2
5 3
6 3
7 3

table 3: stock

variation_id quantity status [0 or 1]
1 10 1
2 15 1
3 0 0
4 0 0
5 0 0
6 3 1
7 0 0

So, with this data, I want to know how many products there are that have at least 1 of its 'variations' of 'status' 1 - in this example it would be 2 (product 1 and 3 have some variations with status 1, product 2 does not).

You just need SUM all the quantity GROUP BY products.id with criteria is stock.status equal 1.

SELECT id, name, SUM(quantity) AS total_quantity
FROM Products pr
LEFT JOIN Variations va ON pr.id = va.product_id
LEFT JOIN Stock st ON st.variation_id = va.id
WHERE st.status = 1
GROUP BY pr.id

Join two tables and apply where filter on status column

select count(*) as cnt
from
products p
join variations v
on p.product_id = v.product_id
where status = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM