问题
Is it possible to sum two values from subqueries?
I need select three values: total_view, total_comments and rating.
Both subqueries is very complicated, so i don't wish duplicate it.
My query example:
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments,
(
total_view * total_comments
) AS rating
FROM products p
WHERE p.status = "1"
ORDER BY rating DESC
回答1:
I would suggest using a subquery:
SELECT p.*, (total_view * total_comments) as rating
FROM (SELECT p.id,
(FIRST subquery) AS total_view,
(SECOND subquery) AS total_comments,
FROM products p
WHERE p.status = '1' -- if status is a number, then remove quotes
) p
ORDER BY rating DESC;
MySQL materializes the subquery. But because the ORDER BY
is on a computed column, it needs to sort the data anyway, so the materialization is not extra overhead.
回答2:
You can't use alias but you can use the same code eg:
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments,
(
(
FIRST subquery
) * (
SECOND subquery
)
) AS rating
FROM products p
WHERE p.status = "1"
ORDER BY rating DESC
回答3:
Simply use a Derived Table to be able to reuse the aliases:
SELECT p.id,
total_view,
total_comments,
total_view * total_comments AS rating
FROM
(
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments
FROM products p
WHERE p.status = "1"
) as dt
ORDER BY rating DESC
来源:https://stackoverflow.com/questions/49358267/mysql-sum-values-from-subqueries