SQL-如何检索包含另一个元素的所有项目的结果集?

时间:2018-08-28 17:34:47

标签: mysql sql group-by having

我将在以下情况下简单解释用例。 基本上,我想从pts_table中查找所有pts / s,其中包含pl001的所有订单

    pl_table
    ========
    pl_id | order_id 
    pl001   order001

    pts_table
    =========
    pts_id | order_id
    pts001  order001
    pts002  order001
    pts002  order002

这是我正在尝试的查询,

    SELECT pts_id
    FROM pts_table
    WHERE pts_table.order_id IN (SELECT DISTINCT(plt.order_id) FROM pl_table 
    as plt where plt.pl_id=pl001)// to check element equality.
    GROUP BY pts_id
    HAVING COUNT(DISTINCT pts_table.order_id) = (SELECT COUNT(plt2.order_id) 
    FROM pl_table as plt2 where plt.pl_id=pl001)//to check size equality.

但是不幸的是,这个查询同时返回了pts001和pts002这是不正确的,它只返回pts001作为结果! 我发现这是由于分组不正确造成的。

有人可以建议我如何更正此问题或其他更好的方法吗? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

这很棘手。它正在检查匹配的订单数量,而不是不匹配的订单数量。因此,pl002未被计入。

SELECT p.pts_id
FROM pts_table p LEFT JOIN
     pl_table p2
     ON p.order_id = p2.order_id AND p2.pl_id = 'pl001'
GROUP BY p.pts_id
HAVING COUNT(*) = COUNT(p2.order_id) AND                                    -- All match
       COUNT(*) = (SELECT COUNT(*) FROM pl_table WHERE pl.pl_id = 'pl001')  -- match all of them

答案 1 :(得分:0)

请考虑以下内容...

create table pl
(pl_id serial primary key
,order_id int not null
);

insert into pl values 
(1,101);

create table pts
(pts_id int not null
,order_id int not null
,primary key(pts_id,order_id)
);

insert into pts values
(1001,101),
(1002,101),
(1002,102);

SELECT DISTINCT a.*
  FROM pts a
  LEFT
  JOIN
     ( SELECT DISTINCT x.*
         FROM pts x
         LEFT
         JOIN pl y
           ON y.order_id = x.order_id
          AND y.pl_id = 1
        WHERE y.pl_id IS NULL
      ) b
     ON b.pts_id = a.pts_id
  WHERE b.pts_id IS NULL;

返回101

http://sqlfiddle.com/#!9/26f411/1