繁体   English   中英

当右表中有很多匹配的行时,左联接

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

我有两张桌子。

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

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

我想选择没有特定状态(即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" = $1
    GROUP BY products.id, products.price  [["id", 11]]

11是产品的ID,应该不会出现在结果中,但是会显示。

I would like to select Products, which don't have orders with specific statuses(ie 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).
    );
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

想法是从产品表开始,并使用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;

暂无
暂无

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

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