MySQL combine two columns and add into a new column

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

I have the following structure with a MySQL table:

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


        
相关标签:
4条回答
  • 2020-11-28 04:04

    SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE

    0 讨论(0)
  • 2020-11-28 04:15

    Add new column to your table and perfrom the query:

    UPDATE tbl SET combined = CONCAT(zipcode, ' - ', city, ', ', state)
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-28 04:25

    Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.

    If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:

    SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;
    

    This way, if the data in the fields changes, you don't have to update your combined field.

    0 讨论(0)
提交回复
热议问题