MySQL CASE SELECT 有更好的方法吗?
最后两个参数是 PHP WHERE 和 ORDER 子句,它们(可能)在这里并不重要。
fornecedores.nome_emp AS nome_fornecedor, exchange_rates1.rate AS rateEUR_USD,
exchange_rates2.rate AS rateEUR_AOA,
CASE produtos.moeda
WHEN 'AOA' THEN produtos.preco_custo / exchange_rates2.rate
WHEN 'EUR' THEN produtos.preco_custo
WHEN 'USD' THEN produtos.preco_custo / exchange_rates1.rate
END as prc,
CASE produtos.moeda
WHEN 'AOA' THEN produtos.preco_venda / exchange_rates2.rate
WHEN 'EUR' THEN produtos.preco_venda
WHEN 'USD' THEN produtos.preco_venda / exchange_rates1.rate
END as pvp
FROM produtos
LEFT JOIN fornecedores ON produtos.id_fornecedor = fornecedores.id_fornecedores
LEFT JOIN exchange_rates AS exchange_rates1 ON exchange_rates1.para = 'USD'
LEFT JOIN exchange_rates AS exchange_rates2 ON exchange_rates2.para = 'AOA'
$whereClause $orderClause
预先感谢:D
The last two parameters are PHP WHERE and ORDER clauses, they (probably) don't matter here.
fornecedores.nome_emp AS nome_fornecedor, exchange_rates1.rate AS rateEUR_USD,
exchange_rates2.rate AS rateEUR_AOA,
CASE produtos.moeda
WHEN 'AOA' THEN produtos.preco_custo / exchange_rates2.rate
WHEN 'EUR' THEN produtos.preco_custo
WHEN 'USD' THEN produtos.preco_custo / exchange_rates1.rate
END as prc,
CASE produtos.moeda
WHEN 'AOA' THEN produtos.preco_venda / exchange_rates2.rate
WHEN 'EUR' THEN produtos.preco_venda
WHEN 'USD' THEN produtos.preco_venda / exchange_rates1.rate
END as pvp
FROM produtos
LEFT JOIN fornecedores ON produtos.id_fornecedor = fornecedores.id_fornecedores
LEFT JOIN exchange_rates AS exchange_rates1 ON exchange_rates1.para = 'USD'
LEFT JOIN exchange_rates AS exchange_rates2 ON exchange_rates2.para = 'AOA'
$whereClause $orderClause
Thanks in advance :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少 MySQL 中
JOIN
的强大功能。您尝试获取两种不同的汇率(通过同一个表的两个不同的LEFT JOIN
),然后使用CASE
来确定使用哪一个。相反,仅加入您实际需要的费率!那么你根本不需要任何条件逻辑。
假设
exchange_rates
中有一行EUR
的汇率设置为1
。You're missing the power of a
JOIN
in MySQL. You're trying to get two different exchange rates (via two differentLEFT JOIN
s to the same table) and then use theCASE
to figure out which one to use.Instead, join only to the rate you actually need! Then you don't need any conditional logic at all.
This assumes that there's a row in
exchange_rates
forEUR
that has the rate set to1
.