2012-09-26 67 views
0

在下面的UNION查詢中,子查詢#2和#4是相同的,我想避免兩次提取相同的數據。據我所知,有些數據庫允許你在查詢開頭寫一個WITH子句,但SQLite不支持它。所以問題是如何優化下面的查詢。SQLite:如何優化UNION查詢

SELECT disliked, recommended, weight 
FROM 
    (SELECT movie_id * 10 AS disliked 
     FROM ratings 
    WHERE rating IN (1,2) 
     AND user_id = #{id} 
    ) AS input, 
    (SELECT movie_id AS recommended, rating AS weight 
     FROM ratings 
    WHERE rating IN (4,5) 
     AND user_id = #{id} 
    ) AS output 
UNION 
SELECT liked, recommended, weight 
FROM 
    (SELECT movie_id, movie_id * 10 + 1 AS liked 
     FROM ratings 
    WHERE rating IN (4,5) 
     AND user_id = #{id} 
    ) AS input, 
    (SELECT movie_id AS recommended, rating AS weight 
     FROM ratings 
    WHERE rating IN (4,5) 
     AND user_id = #{id} 
    ) AS output 
WHERE input.movie_id != recommended 

回答

1

我不能完全肯定我讀過你的權利這快,但也許是這樣的:

SELECT 
    10*r1.movie_id+(r1.rating IN (4,5)) AS likedisliked, 
    r2.movie_id AS recommended, 
    r2.rating AS weight 
FROM ratings AS r1, ratings AS r2 
WHERE r1.user_id=#{id} AND r2.user_id=#{id} 
     AND r1.rating IN (1,2,4,5) AND r2.rating IN (4,5) 
     AND r1.movie_id!=r2.movie_id; 
+0

優秀的解決方案,我已經接受了您的回答,謝謝。 – Toshio

+0

不客氣;-) –