Friday, December 13, 2013

Concat multiple columns and string in Mysql

Yep, here come another simple trick found along the way. How to concat multiple columns and string together in mysql ? Suppose that you want to display the following output:

code         subcode     keycode    name
 5                 1            5-1             dummy 1
 5                  2           5-3             dummy 2
 3                  1           3-1             dummy 3

Our table columns:
 -code
 -subcode
 -name

but keycode does not exist in the table and should be formed from code and subcode.
keycode =  code , '-', subcode

So our query should be:

select code , subcode, concat(code,'-',subcode), name from ourTable;

In fact concat is a mysql built-in function returning a string from its concatenating arguments. Concat may take one, two or more arguments. You may also look into concat_ws() and for more info see http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat

No comments:

Post a Comment