MySQL: sum values from subqueries(MySQL:来自子查询的总和)
问题描述
是否可以对子查询中的两个值求和?
Is it possible to sum two values from subqueries?
我需要选择三个值:total_view、total_comments 和 rating.
I need select three values: total_view, total_comments and rating.
两个子查询都非常复杂,所以我不希望重复它.
Both subqueries is very complicated, so i don't wish duplicate it.
我的查询示例:
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
在计算列上,所以无论如何它都需要对数据进行排序,所以物化不是额外的开销.
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.
这篇关于MySQL:来自子查询的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL:来自子查询的总和
基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01