【发布时间】: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