For example, a COUNT operator can be re-used in a SUM. Take the following two queries:
SELECT story_id, COUNT(*) AS vcount FROM votes GROUP BY story_id;
SELECT story_id, SUM(ratings) AS score FROM
SELECT story_id, rating FROM ratings
UNION
SELECT story_id, 1 FROM votes;
The second query can re-use the first like this:
SELECT story_id, SUM(ratings) AS score FROM
SELECT story_id, rating FROM ratings
UNION
(SELECT story_id, COUNT(*) FROM votes GROUP BY story_id);
For example, a
COUNT
operator can be re-used in aSUM
. Take the following two queries:The second query can re-use the first like this:
to avoid re-counting all of the votes.