这个查询可以优化吗?
ColumnA ColumnB
1 0
2 0
2 1
2 2
3 0
3 0
下面这个查询可以优化吗?
SELECT DISTINCT ColumnA
FROM TABLE
WHERE ColumnA NOT IN (SELECT ColumnA
FROM TABLE
WHERE ColumnB = 2)
AND ColumnB = 0
这应该返回 1 和 3。
我想从 ColumnA 中选择不同的值,但前提是 ColumnB 中有一个值等于 0...并且 ColumnB 中没有值等于 2。是否有更优化的重写方法这?
ColumnA ColumnB
1 0
2 0
2 1
2 2
3 0
3 0
Can this query below be optimized?
SELECT DISTINCT ColumnA
FROM TABLE
WHERE ColumnA NOT IN (SELECT ColumnA
FROM TABLE
WHERE ColumnB = 2)
AND ColumnB = 0
This should return 1 and 3.
I want to select distinct values from ColumnA, but only if there is a value in ColumnB equal to 0... and there is no value in ColumnB equal to 2. Is there a more optimal way to rewrite this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以试试这个:
You could try this:
not in
可能会降低性能。您可以尝试分组,并计算每个组中零和二的数量:我不确定在不检查执行计划的情况下这是否更有效,但因为它更简单,所以很可能是这样。
另外,这是 SQL Server 语法,因此可能需要进行一些调整才能在 Oracle 中运行。
Having a
not in
can be bad for performance. You could try grouping instead, and count the number of zeroes and twos in each group:I'm not sure if this is more efficient without checking the execution plans, but as it's more straightforward it may very well be.
Also, this is SQL Server syntax, so it might need some tweaking to run in Oracle.
我想说这已经是最好的了。真正提高速度的唯一方法是创建此查询的索引视图并将其用作数据源。
I'd say this is about as good as it gets. Only way really to get faster is to make an indexed view of this query and use it as your datasource.
我尽量避免“NOT IN”,可能
是这样吗?
I try to avoid NOT IN whenever possible
maybe this?
这是现实世界的例子吗?表中的行数会只有这么少吗?如果是这样,那么您不太可能进一步优化它,因为表太小了。话虽如此,“not in”不会很好地扩展,你最好使用“notexists”。
Is this a real world example? Will the table only ever have this very small number of rows? If so, then you aren't really likely to be able to optimise it much further, the table is just too small. Having said that, "not in" wont scale very well, you'd be better of to use "not exists".