In the UNION query below, subqueries #2 and #4 are identical, and I would like to avoid fetching the same data twice. From what I know, some databases allow you to write a WITH clause at the beginning of the query, but SQLite does not support it. So the question is how to optimize the query below.
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
I’m not entirely sure I’ve read you right this fast, but maybe something like this: