MySQL: sum values from subqueries

两盒软妹~` 提交于 2021-01-27 21:04:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!