我有一个mysql查询,我需要多次计算ROUND(SUM(temp.total_pq),2)
之类的值,所以我定义了变量以避免重复它们。
但查询中的第5行在结果中返回错误的值。第一次运行时,@diff_client_partner_qtty := ROUND((@partner_qtty_all_runs - @client_qtty_all_runs), 2) AS diff_client_partner_qtty
的值始终为NULL,此后总是为84。
我问内部DBA,他说我不应该在我的查询中使用变量,因为mysql将为变量设置值的顺序是不可预测的,因此我可能得到NULL值。
但为什么呢?也有人可以请求另一种方式,我可以避免重复ROUND(SUM(temp.total_pq),2)
多次以外的子查询。我宁愿避免使用子查询,因为我认为即使在当前形式的查询中也不是那么可读。
SELECT temp.dtaccounted AS accounting_period,
@partner_qtty_all_runs := ROUND(SUM(temp.total_pq),2) AS partner_qtty_all_runs,
ROUND(temp.mmq,2) AS mopay_qtty,
@client_qtty_all_runs := ROUND(SUM(temp.total_cq),2) AS client_qtty_all_runs,
@diff_client_partner_qtty := ROUND((@partner_qtty_all_runs - @client_qtty_all_runs), 2) AS diff_client_partner_qtty,
@partner_gtv := ROUND(temp.total_pq_gtv, 2) AS partner_gtv,
@client_gtv := ROUND(temp.total_cq_gtv,2) AS client_gtv,
@diff_client_partner_gtv := ROUND((@partner_gtv - @client_gtv), 2) AS diff_client_partner_gtv,
temp.stariffcurrency AS tariffcurrency,
ROUND(@diff_client_partner_gtv * ffactor, 2) AS diff_client_partner_gtv_eur,
temp.scountry AS country,
temp.spartnererpid AS partner_erp_id,
c.name AS partner_name,
temp.nproducttype AS product,
temp.capping
FROM
(SELECT SUM(npartnerquantity) AS total_pq,
SUM(nmindmaticsquantity) AS mmq,
SUM(nclientquantity) AS total_cq,
SUM(dgrosstariff * npartnerquantity) AS total_pq_gtv,
SUM(dgrosstariff * nclientquantity) AS total_cq_gtv,
nrun,
vb.scountry,
vb.spartnererpid,
dtaccounted,
stariffcurrency,
vb.nproducttype,
cq.bisenabled AS capping
FROM report_table vb,
client_table cq
WHERE vb.accperiod > '2013-12-01'
AND vb.partnerid = cq.partnerid
AND vb.scountry = cq.scountry
AND vb.nproducttype = cq.nproducttype
AND (cq.dtvalidto IS NULL
OR cq.dtvalidto > vb.accperiod)
GROUP BY scountry,
nproducttype,
partnerid,
nrun,
accperiod
) temp,
customer c,
currency_conversion cc
WHERE temp.partnerid = c.erp_id
AND temp.total_pq <> temp.total_cq
AND cc.scurrencyfrom = temp.stariffcurrency
AND cc.scurrencyto = 'EUR'
AND cc.dtrefdate = temp.accperiod
GROUP BY temp.scountry,
temp.partnerid,
c.name,
temp.nproducttype,
temp.accperiod
ORDER BY temp.accperiod,
temp.scountry,
temp.partnerid,
temp.nproducttype,
temp.capping \G;