我有一个有趣的MySQL查询,需要从另一个表中提取一个子查询,我想知道这是否有可能让mysql计算子查询。
例如:(我不得不用'gte‘和'lte’替换一些括号,因为他们搞乱了post格式)
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
发布于 2011-03-18 04:14:39
创建一个存储函数来为您计算该值,并传递稍后将决定的参数。当您的业务逻辑发生变化时,您只需更新存储的函数。
https://stackoverflow.com/questions/5344568
复制相似问题