MySQL:来自子查询的总和值

时间:2018-03-19 08:07:55

标签: mysql sql subquery

是否可以将子查询中的两个值相加?

我需要选择三个值:total_view,total_comments和rating。

两个子查询都很复杂,所以我不希望重复它。

我的查询示例:

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

3 个答案:

答案 0 :(得分:4)

我建议使用子查询:

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实现了子查询。但由于ORDER BY位于计算列上,因此无论如何都需要对数据进行排序,因此实现不是额外的开销。

答案 1 :(得分:1)

您无法使用别名,但您可以使用相同的代码,例如:

  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

答案 2 :(得分:0)

只需使用派生表即可重用别名:

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