更复杂查询中的 COUNT() 和 SELECT
我目前正在使用以下查询(确实经过简化):
SELECT
(
SELECT COUNT(id)
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
+
(
SELECT COUNT(id)
FROM bla_2
WHERE id NOT IN (SELECT id FROM blahhh)
)
as count
在有人提到它之前,我可以添加 bla_1
和 bla_2
不包含相同的数据,即使这样简化的查询看起来可能是这样。
这里的问题是第二个查询计算的一些 id 已经被第一个查询处理了。换句话说,第二个查询可能返回“2”,并且第一个查询已经对这 2 个计数行中的一个进行了计数。
因此,由于两个查询都有一些共同的 id,我不想计算两次,所以我想到了:
SELECT
(
SELECT COUNT(id)
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
+
(
SELECT COUNT(id)
FROM bla_2
WHERE id NOT IN (SELECT id FROM blahhh)
AND id NOT IN (SELECT id
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
)
as count
您会注意到第二个查询中的第二个子查询 > 与第一个查询完全相同。
我的问题是,如果不执行相同的查询两次(第一次计算结果,第二次实际检索这些结果),我就无法完成这项工作。
非常喜欢解决这个问题的人:-)
I'm currently using the following query (simplified indeed) :
SELECT
(
SELECT COUNT(id)
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
+
(
SELECT COUNT(id)
FROM bla_2
WHERE id NOT IN (SELECT id FROM blahhh)
)
as count
Before somebody mentions it, may i add bla_1
and bla_2
don't contain the same data, even if with that simplified query it might seem so.
The problem here is that some ids counted by the second query are already taken care of by the first one. In other words, the second query could return '2', and one of those 2 counted rows would already be counted by the first query.
So, since both queries have some ids in common that i don't want to count twice, i came up with that :
SELECT
(
SELECT COUNT(id)
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
+
(
SELECT COUNT(id)
FROM bla_2
WHERE id NOT IN (SELECT id FROM blahhh)
AND id NOT IN (SELECT id
FROM bla_1
WHERE id NOT IN (SELECT id FROM blahhh)
)
)
as count
You will notice that the second subquery inside the second query is the exact same query as the first one.
My problem is that i can't get to make this work without executing the same query twice (a first time to count results, and a second time to actually retrieve those results).
Much love to the one solving that problem :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 UNION 操作来消除重复项。
Try using the UNION operation that will eliminate duplicates for you.