在 Oracle 中使用 count 作为条件
我有两个查询,q1
和 q2
。当 q2
没有行时,我想从 q1
返回列。示例:
select a, b, c from t1 where
count(select d, e, f from t2 where ...) == 0
and ...
通常情况下,我只会使用 JOIN
,但在这种情况下,我没有相关的键。
在 Oracle 中执行此操作的最佳方法是什么?
I have two queries, q1
and q2
. I want to return columns from q1
when q2
has no rows. Example:
select a, b, c from t1 where
count(select d, e, f from t2 where ...) == 0
and ...
Normally, I would just use a JOIN
, but in this case, I have no related keys.
What is the best way to do this in Oracle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我假设这些查询是完全独立的,如下所示:
您现在可以使用 with-query
q2
来选择 table_q2 的计数,并将其与条件交叉连接到table_q1
q2.cnt = 0
以便 q1 仅在 q2 的计数为 != 0 时选择记录。以下 select 语句不会返回任何记录:
但此语句会返回:
I assume that those queries are entirely independant, like so:
You can now have a with-query
q2
that selects the count of table_q2 and cross join it totable_q1
with the conditionq2.cnt = 0
so that q1 only selects records if q2's count is != 0.The following select statement returns no records:
But this one does:
应该有效。如果内部查询和外部查询之间存在某种关系,您只需向
NOT EXISTS
子查询添加一个额外的谓词来表达该关系(即table.column_name = table2.column_name< /代码>)。但不需要使子查询相关。
您也不需要在子查询的
SELECT
列表中指定列名称。仅当添加列更改了查询计划(例如,通过强制优化器查询表而不是使用覆盖索引)时才重要。如果你使用这样的东西,你会得到相同的结果,而且可能会稍微快一些。should work. If there were some relationship between the inner query and the outer query, you would just add an additional predicate to the
NOT EXISTS
subquery that expressed that relationship (i.e.table.column_name = table2.column_name
). But there is no need to make the subquery correlated.You also don't need to specify the column names in the
SELECT
list of the subquery. It would only matter if adding the columns changed the query plan (say, by forcing the optimizer to query the table rather than using a covering index). You'll get the same result if you use something like this and it may be slightly faster.也许你可以尝试这样的事情
这里是嵌套查询
will count the number of a certain column. In case it is ZERO, it will return false and query will return nothing or in case it returns anything more than ZERO, it will return TRUE and query will return values.
希望有帮助
maybe you can try something like this
Here the nested query within the
will count the number of a certain column. In case it is ZERO, it will return false and query will return nothing or in case it returns anything more than ZERO, it will return TRUE and query will return values.
Hope it helps
编写一个包含 COUNT 和 GROUP BY 的查询,而不尝试过滤掉 COUNT(x) = 0。您应该会在结果集中看到零。您想要消除的内容。
添加 HAVING 子句:HAVING COUNT(x) <> 0
Write a query that includes COUNT and GROUP BY without trying to filter out COUNT(x) = 0. You should see the zeros in your result set. That you want to eliminate.
Add a HAVING clause: HAVING COUNT(x) <> 0
如果表实际上是在某个字段上连接的(让我们将两者命名为
id
),那么值得构造一个像这样的查询If the tables are in fact joined on some field (let's name it
id
for both), it worth construct a query like检查此查询
已测试
Check this query
Tested