Combining Multiple Table Columns in MySQL

Posted on the August 25th, 2008 under MySQL, Programming, Q&A, Tutorial by Zaki

Question

How to combine address1, address2, address3 and address4 in the following table to a single column such as address?

CREATE TABLE user (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`email` VARCHAR( 255 ) NOT NULL ,
`address1` VARCHAR( 100 ) NOT NULL ,
`address2` VARCHAR( 100 ) NOT NULL ,
`address3` VARCHAR( 100 ) NOT NULL ,
`address4` VARCHAR( 100 ) NOT NULL ,
`postcode` VARCHAR( 6 ) NOT NULL ,
`state` VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM;

Answer

First of all, let alter the table and add columns address and set it as TEXT.

ALTER TABLE `user` ADD `address` TEXT NOT NULL AFTER `email`;

Next on the list, is to migrate existing data from address1, address2, address3 and address4 to address. For this you can either do it with either any programming language including PHP, Ruby-on-Rails but it’s always easier to do it directly with MySQL query, here we will be using CONCAT() function to concat all four columns.

UPDATE `user`
SET `address` = CONCAT(`address1`, "\n", `address2`, "\n", `address3`, "\n", `address4`);

4 Responses to 'Combining Multiple Table Columns in MySQL'

Subscribe to comments with RSS or TrackBack to 'Combining Multiple Table Columns in MySQL'.
  1. max said, on August 29th, 2008 at 11:20 am

    Nice tutorial, very helpful.

  2. azraaai said, on September 13th, 2008 at 4:20 pm

    “address” also can be use when query the table without adding another column.

    for example,
    ———
    SELECT `id`,`name`,`email,`postcode`,`state`, CONCAT(`address1`, “\n”, `address2`, “\n”, `address3`, “\n”, `address4`) as `address`
    ———

  3. admin said, on September 16th, 2008 at 12:46 am

    But the limitation is still there, to edit the value of address we still have to end up using 4 input field to cater address alone while using textarea will cause issue if let say the user key-in more than 4 line.

  4. Ninjabear said, on September 28th, 2008 at 6:23 am

    Not what I was looking for. Is there a way to combine rows from two columns into one col? For example, 10 rows from props.title and 5 rows from tickets.title to make a title column with 15 rows in?

  1. No trackback at the moment.
Leave a Reply
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">