Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

mysql - Setting many rows new field to a specific value based on another field in one query

I'm adding a new column to my CountryCodes table, phoneCodes. I want to add each country's phone code based on the numericCode that already exists in the table. Is there a way to do this without doing a SET for each country? It seems inefficient to do:

UPDATE TABLE `CountryCodes`
SET `phoneCode` = 1
WHERE `numericCode = 840
...
/* Do this for each country?*/
question from:https://stackoverflow.com/questions/65890007/setting-many-rows-new-field-to-a-specific-value-based-on-another-field-in-one-qu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a case expression:

update table countrycodes
    set phonecode = (case when numericCode = 840 then 1
                          . . .
                     end)
    where numericCode in (840, . . .);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...