[英]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? 'variations' 表有 'status' 列,它的值可以是 0 或 1。我想获取至少具有状态 1 变体的产品 (COUNT()) 的数量。如何进行查询? [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): [编辑]好的,我认为如果我简化问题,我将摆脱表结构,但是,这里我们 go (仅与问题相关的列和一些模拟数据):
It's actually 3 linked tables: table 1: 'products'它实际上是 3 个链接表:表 1:“产品”
id ID | name姓名 |
---|---|
1 1 | t-shirt T恤 |
2 2 | shoes鞋 |
3 3 | shorts短裤 |
table 2: variations表 2:变化
id ID | product_id product_id |
---|---|
1 1 | 1 1 |
2 2 | 1 1 |
3 3 | 2 2 |
4 4 | 2 2 |
5 5 | 3 3 |
6 6 | 3 3 |
7 7 | 3 3 |
table 3: stock表 3:库存
variation_id变体_id | quantity数量 | status [0 or 1]状态 [0 或 1] |
---|---|---|
1 1 | 10 10 | 1 1 |
2 2 | 15 15 | 1 1 |
3 3 | 0 0 | 0 0 |
4 4 | 0 0 | 0 0 |
5 5 | 0 0 | 0 0 |
6 6 | 3 3 | 1 1 |
7 7 | 0 0 | 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).因此,有了这些数据,我想知道有多少产品的“状态”1 的“变体”中至少有 1 个 - 在本例中为 2(产品 1 和 3 与状态 1 有一些变体,产品 2 没有)。
You just need SUM
all the quantity GROUP BY
products.id with criteria is stock.status equal 1.您只需要SUM
GROUP BY
products.id 的所有数量,标准为 stock.status 等于 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加入两个表并在状态列上应用 where 过滤器
select count(*) as cnt
from
products p
join variations v
on p.product_id = v.product_id
where status = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.