Reputation: 133
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
Upvotes: 0
Views: 438
Reputation: 143219
I'm not entirely sure I've read you right this fast, but maybe something like this:
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;
Upvotes: 1