[英]Can I get the minimum of 2 columns which is greater than a given value using only one scan of a table
This is my example data (there are no indexes and I do not want to create any): 这是我的示例数据(没有索引,并且我不想创建任何索引):
CREATE TABLE tblTest ( a INT , b INT );
INSERT INTO tblTest ( a, b ) VALUES
( 1 , 2 ),
( 5 , 1 ),
( 1 , 4 ),
( 3 , 2 )
I want the minimum value in of both column a and column b which is greater then a given value. 我想要列a和列b中的最小值都大于给定值。 Eg if the given value is 3 then I want 4 to be returned. 例如,如果给定值为3,则我希望返回4。
This is my current solution: 这是我目前的解决方案:
SELECT MIN (subMin) FROM
(
SELECT MIN (a) as subMin FROM tblTest
WHERE a > 3 -- Returns 5
UNION
SELECT MIN (b) as subMin FROM tblTest
WHERE b > 3 -- Returns 4
)
This searches the table twice - once to get min(a)
once to get min(b)
. 这将搜索表两次-一次获取min(a)
一次获取min(b)
。
I believe it should be faster to do this with just one pass. 我相信只需一关就能做到这一点。 Is this possible? 这可能吗?
You want to use conditional aggregatino for this: 您要为此使用条件聚合:
select min(case when a > 3 then a end) as minA,
min(case when b > 3 then b end) as minB
from tblTest;
To get the minimum of both values, you can use a SQLite extension, which handles multiple values for min()
: 要获得两个值的最小值,可以使用SQLite扩展,该扩展处理min()
多个值:
select min(min(case when a > 3 then a end),
min(case when b > 3 then b end)
)
from tblTest
The only issue is that the min
will return NULL
if either argument is NULL. 唯一的问题是, min
返回NULL
如果任一参数为NULL。 You can fix this by doing: 您可以通过以下方法解决此问题:
select coalesce(min(min(case when a > 3 then a end),
min(case when b > 3 then b end)
),
min(case when a > 3 then a end),
min(case when b > 3 then b end)
)
from tblTest
This version will return the minimum value, subject to your conditions. 此版本将根据您的条件返回最小值。 If one of the conditions has no rows, it will still return the minimum of the other value. 如果其中一个条件没有行,它将仍然返回另一个值的最小值。
From the top of my head, you could modify the table and add a min value column to store the minimum value of the two columns. 从我的头开始,您可以修改表并添加一个最小值列以存储两列的最小值。 then query that column. 然后查询该列。
Or you can do this: 或者您可以这样做:
select min(val)
from
(
select min(col1, col2) as val
from table1
)
where
val > 3
The outer SELECT, queries the memory, not the table itself. 外部SELECT查询内存,而不查询表本身。
Check SQL Fiddle 检查SQL小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.