如何检索包含其他元素的所有项的结果集?

b1uwtaje  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(310)

我将用下面的场景简单地解释用例。基本上,我想从包含pl001的所有订单的pts\表中找到所有的pts/s

  1. pl_table
  2. ========
  3. pl_id | order_id
  4. pl001 order001
  5. pts_table
  6. =========
  7. pts_id | order_id
  8. pts001 order001
  9. pts002 order001
  10. pts002 order002

这是我要问的问题,

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

但不幸的是,这个查询同时返回pts001和pts002,这是不正确的。它应该只返回pts001作为结果!。当我发现这是由于不正确的分组部分。
有人能给我建议如何纠正这个问题或其他更好的方法吗?非常感谢您的帮助。

eagi6jfj

eagi6jfj1#

这很棘手。它是检查匹配的订单数量,而不是不匹配的订单数量。因此,pl002没有进入计数。

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

aelbi1ox2#

考虑以下几点。。。

  1. create table pl
  2. (pl_id serial primary key
  3. ,order_id int not null
  4. );
  5. insert into pl values
  6. (1,101);
  7. create table pts
  8. (pts_id int not null
  9. ,order_id int not null
  10. ,primary key(pts_id,order_id)
  11. );
  12. insert into pts values
  13. (1001,101),
  14. (1002,101),
  15. (1002,102);
  16. SELECT DISTINCT a.*
  17. FROM pts a
  18. LEFT
  19. JOIN
  20. ( SELECT DISTINCT x.*
  21. FROM pts x
  22. LEFT
  23. JOIN pl y
  24. ON y.order_id = x.order_id
  25. AND y.pl_id = 1
  26. WHERE y.pl_id IS NULL
  27. ) b
  28. ON b.pts_id = a.pts_id
  29. WHERE b.pts_id IS NULL;

返回101
http://sqlfiddle.com/#!2011年9月26日

展开查看全部

相关问题