在下面的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
答案 0 :(得分: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;