SQLite:如何优化 UNION 查询
Posted
技术标签:
【中文标题】SQLite:如何优化 UNION 查询【英文标题】:SQLite: How to optimize a UNION query 【发布时间】:2012-09-26 20:50:14 【问题描述】:在下面的 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
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于SQLite:如何优化 UNION 查询的主要内容,如果未能解决你的问题,请参考以下文章