【问题标题】:How to use calculation from select for another calculation如何将 select 中的计算用于另一个计算
【发布时间】:2019-08-09 09:00:46
【问题描述】:

我正在尝试使用从一个选择到另一个选择的命名计算,使用 Ver 15.1 Distrib 10.1.38-MariaDB,对于使用 readline 5.2 的 debian-linux-gnu (x86_64)。

select f.price * t.price as result_price, result_price-30/30 as percentage from table f join table t on f.to_id = t.from_id where f.from_id = 12 and t.to_id=205;

它给了我一个错误“ERROR 1054 (42S22): Unknown column 'result_price' in 'field list'”。如何让它在 select 语句中看到 result_price,或者我只是简单地复制并写“(t.price*f.price - 30) / 30”。 哪个效率更高?

【问题讨论】:

  • 试试(f.price * t.price) as result_price((f.price * t.price)-30/30) as percentage
  • 您不能在查询的SELECT 部分中使用列别名,因为它们不会被及时评估。进行复制。
  • 您也可以使用子查询,但比重复表达式开销更大。

标签: mysql mariadb


【解决方案1】:

您可以将变量分配给计算,然后在查询中重用它。

SELECT @result_price:=f.price*f.price AS result_price, (@result_price - 30)/30 AS percentage FROM ...

【讨论】:

  • 警告:在 8.0 中,不推荐在 SELECT 中进行分配。这意味着它将在未来被删除。
猜你喜欢
  • 2021-09-08
  • 1970-01-01
  • 2010-12-23
  • 2021-07-15
  • 2019-11-23
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 2014-12-08
相关资源
最近更新 更多