简体   繁体   中英

mysql - combining columns into one big column

我有一个地址表...街道地址,城市,州和邮政编码我需要街道地址城市州和在任何列中添加邮政编码

You can just concat them

SELECT CONCAT(address, '  ', city, ', ', state, ' ', zip) FROM table;

If you want to make this more convenient for you in the future or for other users, consider creating a view of the table that does this and provides it as a column named location or the like.

如果需要将合并的值存储在表中,请使用

UPDATE address SET bigcolumn = CONCAT(streetaddress, ', ', city, ', ', state, ' ', zip);

This would help you : string-functions

Concatenating the column values with desired seperators. So an example query in your case can be :

SELECT CONCAT(street-address, '\n', city, ', ',state,'-',zip) as full_address FROM table;

I wouldn't suggest you place all those columns into one column either. You might want to search by city or state or one of the other individual columns later and having them as separate fields would be much easier. You could either just concat the fields as part of a SELECT statement as suggested earlier, or better yet, if it is something that will be done frequently, you could create a VIEW with the fields concatenated and then SELECT the view, or you could simply create a Stored Function that will concat the fields and call the function as part of a SELECT statement. Something like this should work.

CREATE FUNCTION CONCAT_ADDRESS (p_id INT)
  RETURNS VARCHAR(255)
  BEGIN
  DECLARE v_street,v_city,v_state,v_zip, address VARCHAR(255);
  SELECT street_address, city, state, zip 
  INTO v_street,v_city,v_state,v_zip
  FROM table WHERE id = p_id;
  SET address = CONCAT(v_street,', ', v_city,', ', v_state,', ', v_zip);
  RETURN address;
END |

Once the function is created, you can use it anytime as part of a SELECT statement as in:

SELECT id, name, surname, CONCAT_ADDRESS(id) FROM table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM