Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select two columns as one?

Tags:

mysql

I'm trying to search two fields as one from a MySQL database using PHP.

e.g.

mysql_query("   SELECT (first_name,last_name) As name   FROM people   WHERE (name LIKE '%" . $term . "%') "); 

I thought that this was the code to use, but to no avail. It has been a while since I've done this and I can't remember exactly how to achieve the desired result.

like image 368
Bobby Avatar asked Aug 31 '11 11:08

Bobby


People also ask

How do I select multiple columns as single column in SQL?

select column1 || ' ' || column2 as whole_name FROM tablename; Here || is the concat operator used for concatenating them to single column and ( '' ) inside || used for space between two columns.

How do I combine data from multiple columns into one in SQL?

Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.


2 Answers

You're looking for the CONCAT function.

mysql_query("SELECT CONCAT(first_name, last_name) As name FROM people WHERE (CONCAT(first_name, last_name) LIKE '%" . $term . "%')"); 

or even...

mysql_query("SELECT CONCAT(first_name, ' ', last_name) As name FROM people WHERE (CONCAT(first_name, ' ', last_name) LIKE '%" . $term . "%')"); 

I couldn't explain you the reasons behind this (...but maybe someone can leave a comment?), but you can't use the name alias to search for both fields, you have to explicitly CONCAT again.

like image 167
dee-see Avatar answered Sep 22 '22 20:09

dee-see


CONCAT

or

CONCAT_WS

like image 35
Sam Roberts Avatar answered Sep 21 '22 20:09

Sam Roberts