MYSQL查询:检查字段值,进行计算(除法)并更新列值

时间:2015-10-30 06:24:50

标签: php mysql

我需要在包含数百行的MySQL表中进行一些计算。

我有一个名为“VAT-Code”的字段,其中包含代码:1或2

我有一个名为“Price”的字段,其中包含价格

查询应执行以下操作:

如果“VAT-Code”值= 1,则计算"Price" / 1,08 - >更新字段值

如果“VAT-Code”值= 2,则计算“Price" / 1,025 - >更新字段值

好的,我试过这个:

我试过这个:

UPDATE jos_tempcsv SET selling price = CASE `VAT-Code` WHEN = 1 THEN `selling price`/1.08 WHEN = 2 THEN `selling price`/1.025 ELSE NULL END

售价是价格领域

但是我收到以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'price = CASE `VAT-Code` WHEN = 1 THEN `selling price`/1.08 WHEN = 2 THEN `sellin' at line 1

3 个答案:

答案 0 :(得分:2)

您可以UPDATE运行CASE

UPDATE yourtable SET yourfield=CASE `VAT-Code` WHEN 1 THEN `Price`/1.08 WHEN 2 THEN `Price`/1.025 ELSE NULL END;

或者您可以将其作为两个单独的UPDATE运行:

UPDATE yourtable SET yourfield=`Price`/1.08 WHERE `VAT-Code`=1;
UPDATE yourtable SET yourfield=`Price`/1.025 WHERE `VAT-Code`=2;

答案 1 :(得分:0)

您可以尝试以下sql查询:

UPDATE yourtable table1,(SELECT * FROM `yourtable` WHERE VAT-Code = 1) table2 SET table1.yourfield = (table2.price/1.08) WHERE table1.VAT-Code = 1

UPDATE yourtable table1,(SELECT * FROM `yourtable` WHERE VAT-Code = 2) table2 SET table1.yourfield = (table2.price/1.025) WHERE table1.VAT-Code = 1

答案 2 :(得分:0)

此查询现在正常工作:

UPDATE jos_tempcsv SET `selling price` = `selling price`/1.08 WHERE `VAT-Code`=1;

UPDATE jos_tempcsv SET `selling price` = `selling price`/1.025 WHERE `VAT-Code`=2;

一个

中的两个查询
UPDATE jos_tempcsv SET `selling price` = CASE `VAT-Code` WHEN 1 THEN `selling price`/1.08 WHEN 2 THEN `selling price`/1.025 ELSE NULL END;