mysql子查询的正确使用
我的数据库中有这 3 个表:product(id、sku、type、price)
、product_relation(parent_id、child_id)
和 product_stock(product_id、quantity、 in_stock)
。产品之间可能存在关系:X 类型的产品可以是 Y 类型的多个产品的父级(可以由其组成)(关系保存在 product_relation
表中)。在 DB 中,类型 X 的产品的数量始终设置为 0。现在是这样。我只需要获取有库存 (in_stock = true
) 的 X 类型产品(sku
和 id
),并且至少其中一种孩子有 数量 > 0
或 in_stock = true
。
我被困在这个问题上好几个小时了。我无法对此进行很好的查询。我实现的最接近的一个是
SELECT a.`id`, a.`sku` FROM `product` AS a
INNER JOIN `product_stock` AS b
ON a.`id` = b.`product_id`
INNER JOIN `product_relation` AS c
ON c.`child_id` = b.`product_id`
WHERE b.`in_stock` = 1 AND a.`type` = 'X'
,但效果不好,因为缺少许多项目。我不知道这是否可以仅通过连接或子查询来处理 请帮忙。
I have this 3 tables in my DB: product (id, sku, type, price)
, product_relation (parent_id, child_id)
and product_stock (product_id, quantity, in_stock)
. There are possible relations between products: Product of type X can be a parent (can consists of) to several products of type Y (relation kept in product_relation
table). In DB products of type X always have quantity set to 0. Now here is the thing. I need to get only products (sku
and id
) of type X which are in stock (in_stock = true
) and at least one of their children has quantity > 0
or in_stock = true
.
I'm stuck on that for several hours. I can't make a good query for this. The closest one I achieved is
SELECT a.`id`, a.`sku` FROM `product` AS a
INNER JOIN `product_stock` AS b
ON a.`id` = b.`product_id`
INNER JOIN `product_relation` AS c
ON c.`child_id` = b.`product_id`
WHERE b.`in_stock` = 1 AND a.`type` = 'X'
but it's not good, because many items are missing. I don't know if this can be handle by joins only or subqueries have
Help please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全确定我明白你在问什么;这有帮助吗?
I'm not totally sure I understood what you were asking; does this help?
如果您不需要子查询,则不需要它。这里的优点是,如果您想知道哪些子项满足条件,您只需将其字段添加到 select 子句即可。
You don't need a sub query if you don't want it. The advantage here is that if you wanted to know which children met the criteria you could just add its fields to the select clause.