Mysql - 在Mysql Query或where子句中添加if条件

时间:2018-03-12 20:39:29

标签: mysql join

我在MySQL中编写了一个连接查询,该查询运行良好并显示结果。

我正在尝试编写一个MySQL查询,显示2个额外的列和一些计算

 If isPercent=1 then 
New Column1=price*currentPercent/100 
New Column2=LineItemQuantity*price 

我尝试在PHP中编写此查询,但由于有100,000个记录,因此超时。

这是MySQL查询,结果如下所示

Select 
wl.LineItems_LineItemID,
wl.LineItemQuantity, 
pj.IsPercent, 
pj.CurrentPercent,
pj.CurrentRate,
cb.Price 
from 
WorkOrderLineItems wl, 
PayScaleLoaclJObCodes pj, 
ClientBillingRates cb 
where 
wl.LineItems_LineItemID=pj.JobCodeID 
AND wl.LineItems_LineItemID=cb.ClientBillingRates_ID 
AND pj.PayScalesLocal_ID='33'

enter image description here

1 个答案:

答案 0 :(得分:1)

我会用这种方式编写查询:

$(this).text()

与上面的评论一样,我鼓励您使用SELECT wl.LineItems_LineItemID, wl.LineItemQuantity, pj.IsPercent, pj.CurrentPercent, pj.CurrentRate, cb.Price, IF(pj.IsPercent=1, cb.Price*pj.CurrentPercent/100, NULL) AS `New Column 1`, IF(pj.IsPercent=1, wl.LineItemQuantity*cb.Price, NULL) AS `New Column 2` FROM WorkOrderLineItems wl JOIN PayScaleLoaclJObCodes pj ON wl.LineItems_LineItemID = pj.JobCodeID JOIN ClientBillingRates cb ON wl.LineItems_LineItemID = cb.ClientBillingRates_ID WHERE pj.PayScalesLocal_ID = '33' 语法,而不是依赖于老式的逗号样式连接。

至于查询超时,我猜你没有正确的索引来支持这个查询。如果您需要有关查询优化的帮助,则应为查询中的每个表运行JOIN,并将输出发布到您的问题中。

相关问题