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
優秀的解決方案,我已經接受了您的回答,謝謝。 – Toshio
不客氣;-) –