sql合并两个子查询
我有两张桌子。表A
有一个id
列。表B
有一个Aid
列和一个type
列。示例数据:
A: id
--
1
2
B: Aid | type
----+-----
1 | 1
1 | 1
1 | 3
1 | 1
1 | 4
1 | 5
1 | 4
2 | 2
2 | 4
2 | 3
我想从表 A 中获取所有包含一定数量的类型 1 和类型 3 操作的 ID。我的查询如下所示:
SELECT id
FROM A
WHERE (SELECT COUNT(type)
FROM B
WHERE B.Aid = A.id
AND B.type = 1) = 3
AND (SELECT COUNT(type)
FROM B
WHERE B.Aid = A.id
AND B.type = 3) = 1
因此对于上面的数据,应仅返回 id 1
。
我可以以某种方式组合这两个子查询吗?目标是使查询运行得更快。
I have two tables. Table A
has an id
column. Table B
has an Aid
column and a type
column. Example data:
A: id
--
1
2
B: Aid | type
----+-----
1 | 1
1 | 1
1 | 3
1 | 1
1 | 4
1 | 5
1 | 4
2 | 2
2 | 4
2 | 3
I want to get all the IDs from table A where there is a certain amount of type 1 and type 3 actions. My query looks like this:
SELECT id
FROM A
WHERE (SELECT COUNT(type)
FROM B
WHERE B.Aid = A.id
AND B.type = 1) = 3
AND (SELECT COUNT(type)
FROM B
WHERE B.Aid = A.id
AND B.type = 3) = 1
so on the data above, just the id 1
should be returned.
Can I combine the 2 subqueries somehow? The goal is to make the query run faster.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
postgres 支持 CTE 吗?
我建议比较执行计划,但我怀疑它会相似,因为所有内容都应该在执行之前崩溃。
Does postgres support CTEs?
I'd suggest comparing the execution plans, but I suspect it would be similar since everything should get collapsed before execution.
这在 TSQL 中有效,在 Postgres 中也有效吗?
This works in TSQL, does it work in Postgres?
另一种选择:
不过,我怀疑这会比你原来的表现更好。
您似乎正在采取最好的策略:仅计算候选行。
也许一些多余的预过滤可能会有所帮助:
Another alternative:
I doubt this will perform better than your original, though.
You seem to be doing the best strategy: counting only the candidate rows.
Perhaps some redundant prefiltering might help: