繁体   English   中英

MySQL:子查询中的值求和

[英]MySQL: sum values from subqueries

是否可以对子查询中的两个值求和?

我需要选择三个值: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

我建议使用子查询:

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位于计算列上,因此无论如何都需要对数据进行排序,因此实现不会产生额外的开销。

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

  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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM