减少冗余的SQLite嵌套查询?

时间:2017-06-07 17:01:09

标签: sqlite subquery query-optimization

如何在检查AA之前减少此嵌套查询以便过滤X,Y,Z? 这可以工作,但是很昂贵,因为它为每个子查询计算X,Y,Z。 每个都只需要检查AA。

SELECT 3*b3.bin3 + 2*b2.bin2 + b1.bin1 FROM 
  (SELECT count(*) AS bin1 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 1 AND `AA` <= 2) b1
  JOIN
  (SELECT count(*) AS bin2 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 2.01 AND `AA` <= 3) b2
  JOIN
  (SELECT count(*) AS bin3 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 3.01 AND `AA` <= 4) b3;

2 个答案:

答案 0 :(得分:0)

你是SQL 2008的人吗?你也许可以用as。试试这个

With b as
(
Select
*
from TD
where 
x=1 and
y >= 2 and
z >= 2)

SELECT 3*b3.bin3 + 2*b2.bin2 + b1.bin1 FROM 

(select
count ()
from b
where AA >= 1 and AA <= 2) bin1
join

(select
count ()
from b
where AA >= 2.01 and AA <= 3) bin2
join

(select
count ()
from b
where AA >= 3.01 and AA <= 4) bin3    

答案 1 :(得分:0)

--REDUCED FORM from Golden Ratio's hint.
WITH `v` AS
(SELECT `AA` FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2)
SELECT 3*bin3 + 2*bin2 + bin1 FROM
  (SELECT count(*) AS bin1 FROM `v` WHERE
  `AA` >= 1 AND `AA` <= 2)
  JOIN
  (SELECT count(*) AS bin2 FROM `v` WHERE
  `AA` >= 2.01 AND `AA` <= 3)
  JOIN
  (SELECT count(*) AS bin3 FROM `v` WHERE
  `AA` >= 3.01 AND `AA` <= 4);