当右侧有很多匹配行时左连接 table

Left join when there are lots of matched rows from right table

我有两张桌子。

Product(id, name)
LineItem(id, product_id, order_id)
Order(id, state)

订单可以有很多产品。一个商品可以同时属于多个订单。

我想要 select 个产品,这些产品没有特定状态的订单(即 1、2)。

我的查询是

SELECT products.id, products.price
  FROM "products"
    LEFT OUTER JOIN line_items ON line_items.product_id = products.id
    LEFT OUTER JOIN orders ON orders.id = line_items.order_id AND orders.status IN (1, 2)
    WHERE (products.price > 0) AND (orders.id IS NULL) AND "products"."id" = 
    GROUP BY products.id, products.price  [["id", 11]]

11 是产品的 ID,不应出现在结果中,但它确实出现了。

select p.id, p.name
from products p
join lineitem l on l.product_id = p.id
join `order` o on l.order_id = o.id
group by p.id, p.name
having sum(case when o.state in (1,2) then 1 else 0 end) = 0

想法是从产品 table 开始,然后使用 left join 查找带有 1 或 2 的订单。如果它们不存在,那么您需要产品:

select p.id, p.name
from product p left join
     lineitem li
     on li.product_id = p.id left join
     orders o  -- a better name for the table
     on li.order_id = o.id and
        o.state in (1, 2)
where o.id is null
group by p.id, p.name;

I would like to select Products, which don't have orders with specific statuses(i.e. 1, 2).

SELECT * FROM products p    -- I would like to select Products
WHERE NOT EXISTS(           --  , which don't have
    SELECT *
    FROM orders o           -- orders 
    JOIN line_items li ON li.order_id = o.id
    WHERE li.product_id = p.id
    AND o.status IN (1,2) -- with specific statuses(i.e. 1, 2).
    );