当右表中有许多匹配的行时左连接

时间:2016-09-17 16:12:34

标签: sql postgresql psql

我有两张桌子。

jquery-ui

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

我想选择没有特定状态订单的产品(即1,2)。

我的查询

( function($, undefined ) {
    $.widget( "ui.sortable", $.ui.sortable, {
        ...
    });
}(jQuery) );

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

3 个答案:

答案 0 :(得分:2)

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).
    );

答案 1 :(得分:1)

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

答案 2 :(得分:1)

我们的想法是从产品表开始,然后使用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;