MySQL CASE SELECT 有更好的方法吗?

发布于 2024-09-26 15:22:41 字数 871 浏览 7 评论 0原文

最后两个参数是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黒涩兲箜 2024-10-03 15:22:41

您缺少 MySQL 中 JOIN 的强大功能。您尝试获取两种不同的汇率(通过同一个表的两个不同的LEFT JOIN),然后使用CASE 来确定使用哪一个。

相反,仅加入您实际需要的费率!那么你根本不需要任何条件逻辑。

fornecedores.nome_emp AS nome_fornecedor, exchange_rates.rate, produtos.preco_custo / exchange_rates.rate
FROM produtos
LEFT JOIN exchange_rates ON exchange_rates.para = produtos.moeda

假设 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 different LEFT JOINs to the same table) and then use the CASE 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.

fornecedores.nome_emp AS nome_fornecedor, exchange_rates.rate, produtos.preco_custo / exchange_rates.rate
FROM produtos
LEFT JOIN exchange_rates ON exchange_rates.para = produtos.moeda

This assumes that there's a row in exchange_rates for EUR that has the rate set to 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文