MySQL评估结果

时间:2011-03-17 20:03:56

标签: mysql conditional subquery statements

我有一个有趣的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',顺便说一下,a.formulae有大约30种不同的可能性,并且它们经常变化,所以在多个if语句中的硬敲击不是真正的选择。 [重新设计业务逻辑的可能性更大!]

无论如何,有什么想法吗?这甚至会起作用吗?

-Thanks -Sean

1 个答案:

答案 0 :(得分:0)

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