如何在sqlite中重用子查询的结果

时间:2013-10-23 09:23:43

标签: sql sqlite subquery

使用SQLite处理移动项目时,我遇到了类似于以下代码的查询:

SELECT col_aa, col_ab FROM tbl_a
WHERE col_ac IN (SELECT col_ba FROM tbl_b WHERE col_bb IN (SELECT col_ca FROM tbl_c WHERE col_cb = 1))
AND col_ad IN (SELECT col_ba FROM tbl_b WHERE col_bb IN (SELECT col_ca FROM tbl_c WHERE col_cb = 1))

很明显,这些子查询是多余的和浪费的。

经过一些研究,似乎CTE,公用表表达式可能是一个解决方案,但SQLite上没有该功能。 (因此,我不确定WITH temp AS语句是否有效)

有没有更好的方法来重构查询以重用子查询的结果?

2 个答案:

答案 0 :(得分:0)

假设tbl_b.col_ba是主键(或只是唯一字段),简单JOIN应该有帮助。试试这个SQL:

SELECT 
  col_aa, 
  col_ab 
FROM 
  tbl_a JOIN
    (
      SELECT col_ba 
      FROM tbl_b 
      WHERE col_bb IN 
       (
         SELECT col_ca 
         FROM tbl_c 
         WHERE col_cb = 1
       )
    ) T2 ON (col_ac = T2.col_ba AND col_ad = T2.col_ba) 

希望它会有所帮助

答案 1 :(得分:0)

您可以创建一个视图,如下所示。...(对不起,代码未经测试)

CREATE VIEW my_view AS 
SELECT col_ba FROM tbl_b WHERE col_bb IN (SELECT col_ca FROM tbl_c WHERE col_cb = 1)

SELECT col_aa, col_ab FROM tbl_a
WHERE col_ac IN (SELECT col_ba FROM my_view)
AND col_ad IN (SELECT col_ba FROM my_view)