sql - 检查多个表中是否存在一组值
问题描述
我想知道检查一组值是否是另一个值的子集的更好方法。
出于某种原因,我无法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
因为table3
不line_id
包含1
和2
。
但是,如果table3
如下所示:
+----+-----------+
| id | table1_id |
+----+-----------+
| 1 | 2 |
| 2 | 1 |
+----+-----------+
它会回来true
我的方法已经很好了吗?如果我IN
正确使用,它会更快吗?还有其他一些我完全想念的方式吗?
解决方案
您可以只使用内部连接并计算结果:
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)
加入将比数组比较快得多。
推荐阅读
- python - LIKE 在 python lambda 表达式中
- r - 如何在 Rmarkdown 中编写集合的交集和并集
- r - 在R中添加两个向量之间的每个组合
- javascript - 如何为具有 2 个网页的产品编写赛普拉斯测试?
- javascript - 浏览器如何处理包含内联事件处理程序的废弃/销毁页面元素
- kubernetes - 如何为在 GKE 上运行的 Kubernetes 服务定义服务标签
- node.js - 通过 API 网关调用 NodeJS lambda 函数时出现服务器错误
- ios - 如何从 Xamarin iOS Google Maps 上的字符串值创建制造商
- deno - 如何在 Deno 中调试 OOM 崩溃
- graph - 你能像我们在 Neo4J 图中那样在 Gremlin Tinkerpop 中为一个顶点设置多个标签吗?