繁体   English   中英

按订单类型过滤产品

[英]Filter products by orders type

我正在尝试以“已分配”类型的订单获取所有产品。 但是我的 sql 有问题,我认为where orders.id in ()是问题所在。 但我不知道该怎么做。

产品有许多不同类型的订单(已分配、退役、服务)。 我需要过滤“已分配”类型的最新订单中的产品,不包括“服务”。

select `products`.`id` from `products` 
inner join `orders_products` on `products`.`id` = `orders_products`.`product_id` 
inner join `orders` on `orders_products`.`order_id` = `orders`.`id` 
where orders.id in (
    select MAX(order_id) from `orders_products` 
    where `product_id` = products.id
) 
and `orders`.`type_id` in (
    select `id` from `order_types` where `code` in ('assigned')
) 
group by products.id

样本数据

order_types

[
  {id: 1, code: "assigned"},
  {id: 2, code: "retired"},
  {id: 3, code: "service"},
]

产品

[
  {id: 1},
  {id: 2},
  {id: 3},
  {id: 4},
  {id: 5}
]

订单

[
  {id: 1, type_id: 1}, // assigned
  {id: 2, type_id: 3}, // service
  {id: 3, type_id: 3}, // service
  {id: 4, type_id: 2}, // retired
  {id: 5, type_id: 1}, // assigned
  {id: 6, type_id: 3}, // service
  {id: 7, type_id: 3}, // service
]

订单产品

[
  {order_id: 1, product_id: 1}, <--
  {order_id: 2, product_id: 1},
  {order_id: 3, product_id: 2},
  {order_id: 4, product_id: 3},
  {order_id: 5, product_id: 4}, <--
  {order_id: 6, product_id: 4},
  {order_id: 7, product_id: 5},
]

寻找结果

SQL 必须退回产品 id 1, 4

这回答了问题的原始版本。

你所描述的听起来像:

select op.product_id
from orders_products op join
     orders o
     on op.order_id = o.id join
     order_types ot
     on ot.id = oo.type_id and
        ot.code = 'assigned'
group by op.product_id;

笔记:

  • 表别名使查询更易于编写和阅读。
  • 反引号只会让一切看起来凌乱、难以书写、难以阅读。
  • 我认为您的where子句中没有第一个子查询的理由。
  • 您不需要products表,因为产品 id 在order_products中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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