我有一个名为“quot_items”的表,其中包含一个 grand_total 字段。它有这样的结构
tender_id | grand_total
15001 100000
15002 250000
15003 1500000
16009 4500000
我有另一个名为“quotation”的表,其中包含一个“类别”字段。它具有这种结构。
tender_id | category
15001 H
15002 E
15003 B
16009 A
我正在尝试的是我需要在 MYSQL 中有特定条件的 UPDATE 语句:
如果 [grand_total'] < '100000') 则类别 H(这意味着如果表 'quot_items' 的总计值 < 100000 则将表 'quotation' 类别字段更新为 'H'。
如果 (['grand_total'] >= '100000') && (['grand_total'] <= '200000') 那么类别 'G'。
如果 (['grand_total'] > '200000') && (['grand_total'] <= '600000') 那么类别 'F'。
如果 (['grand_total'] > '600000') && (['grand_total'] <= '1000000') 那么类别 'E'。
如果 (['grand_total'] > '1000000') && (['grand_total'] <= '1500000') 那么类别 'D'。
还有更多的条件。我需要一个查询来在 MYSQL 中执行此操作,以便我可以在一个更新语句中更新我的数据库。请任何人都可以帮助我。
我尝试了以下方法:
UPDATE quotation INNER JOIN quotation_items ON quotation.tender_id = quotation_items.tender_id
SET quotation.category = (
CASE WHEN quotation_items.grand_total < 100000 then 'H'
WHEN quotation_items.grand_total >= 100000 && quotation_items.grand_total <= 200000 then 'G'
WHEN quotation_items.grand_total > 200000 && quotation_items.grand_total <= 600000 then 'F'
WHEN quotation_items.grand_total > 600000 && quotation_items.grand_total <= 1000000 then 'E'
WHEN quotation_items.grand_total > 1000000 && quotation_items.grand_total <= 1500000 then 'D'
END
);
最佳答案
试试这个:
UPDATE quotation t1
INNER JOIN quot_items t2
ON t1.tender_id = t2.tender_id
SET t1.category =
CASE WHEN t2.grand_total < 100000 THEN 'H'
WHEN grand_total >= 100000 AND grand_total <= 200000 THEN 'G'
WHEN grand_total > 200000 AND grand_total <= 600000 THEN 'F'
WHEN grand_total > 600000 AND grand_total <= 1000000 THEN 'E'
WHEN grand_total > 1000000 AND grand_total <= 1500000 THEN 'D'
ELSE t1.category
END
关于mysql - 根据mysql中另一个表中的值更新一个表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279025/