2015-07-11 74 views
1

我想重用SQLite中的表。我嘗試如下:如何與UNION一起使用表格?

SELECT 
    Partials.e_sentence 
FROM 
     (SELECT 
      e_sentence, _id 
     FROM 
      Pair 
       JOIN PairCategories 
        ON 
         _id=PairId AND CategoryId=53 

     UNION 

     SELECT 
      e_sentence, _id 
     FROM 
      Pair 
     WHERE 
      e_sentence LIKE '%' || 'how often' || '%' 
     GROUP BY 
      e_sentence) 
    AS Parents JOIN Partials 
     ON Parents._id=ParentId 

UNION 

SELECT 
    e_sentence 
FROM 
    Parents 

我試圖完成的關鍵部分是在底部,,我嘗試UNION在前面的語句創建一個表。有沒有辦法在SQLite中做到這一點,或者我不得不重複在UNION的前半部分製作Parents表的查詢?

回答

1

在SQLite的3.8.3或更高版本,你可以使用一個common table expression

WITH Parents AS (
    SELECT e_sentence, _id 
    FROM Pair 
    JOIN PairCategories 
    ... 
) 
SELECT Partials.e_sentence 
FROM Parents 
JOIN Partials ON Parents._id = ParentId 
UNION 
SELECT e_sentence 
FROM Parents; 

如果你使用的是老式的SQLite(可能是因爲你使用的是older Android),您可以創建一個view爲子查詢:

CREATE VIEW Parents AS 
    SELECT e_sentence, _id 
    FROM Pair 
    JOIN PairCategories 
    ...; 

SELECT Partials.e_sentence 
FROM Parents 
JOIN Partials ON Parents._id = ParentId 
UNION 
SELECT e_sentence 
FROM Parents; 

如果你不希望有這種說法永久保存在數據庫中,你可以把它臨時(CREATE TEMPORARY VIEW ...),因此它是不適用於當前數據庫連接之外,或者作爲最後一招,喲你可以插入子查詢無論你使用Parent

SELECT Partials.e_sentence 
FROM (SELECT ...) AS Parents 
JOIN Partials ON Parents._id = ParentId 
UNION 
SELECT e_sentence 
FROM (SELECT ...) AS Parents; 
+0

這正是我正在尋找!我希望我能給你更多的積分,因爲你爲我節省了很多頭腦。這是一個恥辱StackOverflow的獎勵系統有利於簡單和簡單的答案,而不是經過深思熟慮和涉及時間的答案:) –

相關問題