[英]Update MySQL column in one table based on the number of rows in another table
[英]Update column in one table based on value in another table in mysql
我有一個名為“ quot_items”的表,其中包含一個grand_total字段。 它具有這種結構
tender_id | grand_total
15001 100000
15002 250000
15003 1500000
16009 4500000
我還有一個名為“ quotation”的表,其中包含一個“ category”字段。 它具有這種結構。
tender_id | category
15001 H
15002 E
15003 B
16009 A
我正在嘗試的是我需要在某些條件下的MYSQL中的UPDATE語句:
如果[grand_total'] <'100000'),則類別H(這意味着表'quot_items'的grand_total值小於<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語句中更新我的數據庫。 請任何人都可以幫助我。
我嘗試了以下方法:
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
);
使用CASE
表達式。
詢問
SELECT tender_id,
CASE WHEN grand_total < 100000 then 'H'
WHEN grand_total >= 100000 && grand_total <= 200000 then 'G'
WHEN grand_total > 200000 && grand_total <= 600000 then 'F'
WHEN grand_total > 600000 && grand_total <= 1000000 then 'E'
WHEN grand_total > 1000000 && grand_total <= 1500000 then 'D'
END AS Category
FROM quot_items;
以及是否要更新category
列。 然后,
UPDATE quot_items
SET category = (
CASE WHEN grand_total < 100000 then 'H'
WHEN grand_total >= 100000 && grand_total <= 200000 then 'G'
WHEN grand_total > 200000 && grand_total <= 600000 then 'F'
WHEN grand_total > 600000 && grand_total <= 1000000 then 'E'
WHEN grand_total > 1000000 && 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.