mysql - 根据mysql中另一个表中的值更新一个表中的列

标签 mysql sql-update case

我有一个名为“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/

相关文章:

mysql - MYSQL 用 JOIN 改变表

mysql - 是否可以在 UPDATE 的 WHERE 部分使用 Max()

python - 创建可能案例的简单方法

mysql - 统一Mysql中不同日期格式的字段

PHP/mysql - 我的时间戳不喜欢在大于 (>) 语句中

c# - 如何在 C# 中与本地数据库同步时避免远程数据库中的重复

MySQL UPDATE - 更新多行?

mysql - 使用 HSQLDB sqltool 探索 MySQL 文件

php - 在 PHP 中验证后数据未插入数据库

mysql - SQL case 子查询 + 子查询 > 0