0

在下面的 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
4

1 回答 1

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; 
于 2012-09-26T21:10:53.780 回答