【问题标题】:MySQL evaluating resultsMySQL 评估结果
【发布时间】:2011-07-17 16:55:05
【问题描述】:

我有一个有趣的 MySQL 查询需要从另一个表中提取子查询,我想知道这是否有可能让 mysql 评估子查询。

示例: (我不得不用“gte”和“lte”替换一些括号,因为它们搞砸了帖子格式)


select a.id,a.alloyname,a.label,a.symbol, g.grade,
    if(a.id = 1,(
        (((select avg(cost/2204.6) as averageCost from nas_cost where cost != '0' and `date` lte '2011-03-01' and `date` gte '2011-03-31') - t.value) * (astm.astm/100) * 1.2)
    ),(a.formulae)) as thisValue
from nas_alloys a 
left join nas_triggers t on t.alloyid = a.id
left join nas_astm astm on astm.alloyid = a.id
left join nas_estimatedprice ep on ep.alloyid = a.id
left join nas_grades g on g.id = astm.gradeid
where a.id = '1' or a.id = '2'
order by g.grade;

所以当 IF 语句不是 = '1' 时, (a.formulae) 是 nas_alloys 表中的值,即:

((ep.estPrice - t.value) * (astm.astm/100) * 0.012)

基本上我希望这个查询运行为:


select a.id,a.alloyname,a.label,a.symbol, g.grade,
    if(a.id = 1,(
        (((select avg(cost/2204.6) as averageCost from nas_cost where cost != '0' and `date` gte '2011-03-01' and `date` lte '2011-03-31') - t.value) * (astm.astm/100) * 1.2)
    ),((ep.estPrice - t.value) * (astm.astm/100) * 0.012)) as thisValue
from nas_alloys a 
left join nas_triggers t on t.alloyid = a.id
left join nas_astm astm on astm.alloyid = a.id
left join nas_estimatedprice ep on ep.alloyid = a.id
left join nas_grades g on g.id = astm.gradeid
where a.id = '1' or a.id = '2'
order by g.grade;

当 a.id != '1', btw 时,a.formulae 有大约 30 种不同的可能性,并且它们经常更改,因此很难在多个 if 语句中敲打并不是一个真正的选择。 [重新设计业务逻辑的可能性更大!]

无论如何,有什么想法吗?这还能用吗?

-谢谢 -肖恩

【问题讨论】:

    标签: mysql conditional subquery statements


    【解决方案1】:

    创建一个存储函数来为您计算该值,并传递您稍后将决定的参数。当您的业务逻辑发生变化时,您只需更新存储函数即可。

    【讨论】:

    • 我无权创建函数或存储过程 [共享主机] - 不能这样做。此外 - 计算过于频繁 - 用户必须能够更新它们。
    猜你喜欢
    • 2013-01-27
    • 2020-01-19
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2015-04-30
    • 2012-08-23
    相关资源
    最近更新 更多