简体   繁体   English

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

[英]COUNT() and SELECT inside a more complex query

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. 在有人提到它之前,我可以添加bla_1bla_2不包含相同的数据,即使使用简化查询看起来也是如此。

The problem here is that some ids counted by the second query are already taken care of by the first one. 这里的问题是,第二个查询计算的某些ID已由第一个查询处理。 In other words, the second query could return '2', and one of those 2 counted rows would already be counted by the first query. 换句话说,第二个查询可能返回“ 2”,并且这两个计数行中的一个将已经被第一个查询计数。

So, since both queries have some ids in common that i don't want to count twice, i came up with that : 因此,由于两个查询都有一些共同的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

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 :-) 对于解决这个问题的人非常钟爱:-)

Try using the UNION operation that will eliminate duplicates for you. 尝试使用UNION操作,它将为您消除重复。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM