更复杂查询中的 COUNT() 和 SELECT

发布于 2024-12-03 22:42:13 字数 1006 浏览 0 评论 0原文

我目前正在使用以下查询(确实经过简化):

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_1bla_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总攻大人 2024-12-10 22:42:13

尝试使用 UNION 操作来消除重复项。

SELECT COUNT(ID) AS MyCount
FROM 
(  SELECT ID FROM Table1 WHERE /*....*/
   UNION 
   SELECT ID FROM Table2 WHERE /*....*/
) r

Try using the UNION operation that will eliminate duplicates for you.

SELECT COUNT(ID) AS MyCount
FROM 
(  SELECT ID FROM Table1 WHERE /*....*/
   UNION 
   SELECT ID FROM Table2 WHERE /*....*/
) r
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文