MySQL combine two columns and add into a new column

后端 未结 4 521
执念已碎
执念已碎 2020-11-28 03:39

I have the following structure with a MySQL table:

+----------------+----------------+----------+
|    zipcode     |      city      |   state  |
+-----------         


        
4条回答
  •  伪装坚强ぢ
    2020-11-28 04:18

    Create the column:

    ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);
    

    Update the current values:

    UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);
    

    Update all future values automatically:

    CREATE TRIGGER insert_trigger
    BEFORE INSERT ON yourtable
    FOR EACH ROW
    SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
    
    CREATE TRIGGER update_trigger
    BEFORE UPDATE ON yourtable
    FOR EACH ROW
    SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
    

提交回复
热议问题