Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concat two columns into one with the existing column name in mysql?

Tags:

mysql

I want to concatenate two columns in a table with a existing column name using mysql.

An example: I am having a column FIRSTNAME and LASTNAME and so many columns also. I want to concatenate these two columns with the name of FIRSTNAME only.

So I tried like this:

 SELECT *, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`; 

but it displaying the two fields with the name of FIRSTNAME. one field is having normal values and another one is having concatenated values. I want only one column with those concatenate value. I can select single columns, but am having more than 40 columns in my table.

Is there any way to remove the original column using mysql itself?

like image 928
Manik Avatar asked Nov 29 '13 11:11

Manik


People also ask

How do you concatenate column names?

Let's say you want to create a single Full Name column by combining two other columns, First Name and Last Name. To combine first and last names, use the CONCATENATE function or the ampersand (&) operator.

How do I concatenate multiple columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function. The syntax is as follows. Let us first see using CONCAT().

How do I concatenate two columns in query?

Select two or more columns that you need to merge. To select more than one column contiguously or discontiguously, press Shift+Click or CTRL+Click on each subsequent column. The order of selection sets the order of the merged values. Select Transform > Merge Columns.


1 Answers

As aziz-shaikh has pointed out, there is no way to suppress an individual column from the * directive, however you might be able to use the following hack:

SELECT CONCAT(c.FIRSTNAME, ',', c.LASTNAME) AS FIRSTNAME,        c.* FROM   `customer` c; 

Doing this will cause the second occurrence of the FIRSTNAME column to adopt the alias FIRSTNAME_1 so you should be able to safely address your customised FIRSTNAME column. You need to alias the table because * in any position other than at the start will fail if not aliased.

Hope that helps!

like image 103
Raad Avatar answered Oct 20 '22 23:10

Raad