在下面的 UNION 查询中,子查询 #2 和 #4 是相同的,我想避免两次获取相同的数据。据我所知,有些数据库允许你WITH
在查询的开头写一个子句,但 SQLite 不支持。所以问题是如何优化下面的查询。
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