首页 > 解决方案 > 检查多个表中是否存在一组值

问题描述

我想知道检查一组值是否是另一个值的子集的更好方法。

出于某种原因,我无法IN工作,所以我使用了这样的方法:

-- check if `table1.id` is in other tables
SELECT (
  -- check if all `table1.id` is in table2's `table1_id`
  ARRAY(SELECT id FROM table1) <@ ARRAY(SELECT table1_id FROM table2)
    AND
  -- check if all `table1.id` is in table3's `table1_id`
  ARRAY(SELECT id FROM table1) <@ ARRAY(SELECT table1_id FROM table3)
  -- ...and so on
)

例如,如果我有这两行table1

+----+
| id |
+----+
|  1 |
|  2 |
+----+

这两行在table2

+----+-----------+
| id | table1_id |
+----+-----------+
|  1 |         1 |
|  2 |         2 |
+----+-----------+

而这一行在table3

+----+-----------+
| id | table1_id |
+----+-----------+
|  1 |         2 |
+----+-----------+

结果将是false因为table3line_id包含12

但是,如果table3如下所示:

+----+-----------+
| id | table1_id |
+----+-----------+
|  1 |         2 |
|  2 |         1 |
+----+-----------+

它会回来true

我的方法已经很好了吗?如果我IN正确使用,它会更快吗?还有其他一些我完全想念的方式吗?

标签: sqlpostgresql

解决方案


您可以只使用内部连接并计算结果:

with table1_count as (
  select count(*) as count
  FROM table1
),
all_table_count as (
  select count(*) as count
    from (
    select table1.id from table1
    join table2 on table1.id = table2.table1_id
    join table3 on table1.id = table3.table1_id
  ) sub
)
select table1_count.count = all_table_count.count as ids_everywhere
from all_table_count,table1_count
;
 ids_everywhere
----------------
 f
(1 row)

加入将比数组比较快得多。


推荐阅读