如何编写使用多个BETWEEN优化的SQL查询?

时间:2015-05-12 20:18:10

标签: sql sqlite

我正在使用SQLite,我想知道如何概括以下SQL语句,以便可以对任意数量的列施加不等式条件,而不仅仅是列x

SELECT * FROM t WHERE x BETWEEN xMin AND xMAX

我预计这可以通过以下方式实现,但无济于事:

SELECT * FROM t 
WHERE (x BETWEEN xMin AND xMAX) 
  AND (y BETWEEN yMin AND yMax) 
  AND (z BETWEEN zMin AND zMax) ...

欢迎任何建议。

3 个答案:

答案 0 :(得分:1)

你的陈述应该有用,例如与Oracle合作:

SELECT * 
  FROM (SELECT 10 x, 40 y, 50 z 
          FROM dual) 
 WHERE (x BETWEEN 8 AND 12)
   AND (y BETWEEN 30 AND 42) 
   AND (z BETWEEN 0 AND 100);

Fiddle demo。使用My SQL:

SELECT * 
  FROM (SELECT 10 AS x, 40 AS y, 50 AS z) AS t
 WHERE (x BETWEEN 8 AND 12)
   AND (y BETWEEN 30 AND 42) 
   AND (z BETWEEN 0 AND 100);

另一个MySQL FiddleSQLite FiddlePostgreSQL Fiddle:)

p.s。 (根据评论更新):小心,

SELECT * 
  FROM (SELECT "10" AS x, "40" AS y, "50" AS z) AS t
 WHERE (x BETWEEN 8 AND 12)
   AND (y BETWEEN 30 AND 42) 
   AND (z BETWEEN 0 AND 100);

,也不

SELECT * 
  FROM (SELECT 10 AS x, 40 AS y, 50 AS z) AS t
 WHERE (x BETWEEN "8" AND "12")
   AND (y BETWEEN 30 AND 42) 
   AND (z BETWEEN 0 AND 100);

的工作原理。两者都在 DB Browser for SQLite sqlitebrowser.org)中执行失败。

答案 1 :(得分:1)

在SQLite 3中运行良好。

sqlite> CREATE TABLE test (x INT, y INT , z INT);
sqlite> INSERT INTO test (x,y,z) VALUES (1,2,3), (2,3,4), (4,5,6);
sqlite> SELECT * FROM test WHERE (x BETWEEN 0 AND 5) AND (y BETWEEN 0 AND 5) AND (z BETWEEN 0 AND 5)
   ...> ;
1|2|3
2|3|4
sqlite>

答案 2 :(得分:-2)

试试这个:

Select * from t where x >=xmin and x <= xmax and y >=ymin and y<= ymax...