4

在使用 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 语句是否有效)

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

4

2 回答 2

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) 

希望它会有所帮助

于 2013-10-28T23:57:29.880 回答
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)
于 2019-04-02T20:33:39.917 回答