Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat a string to SELECT * MySql

The following query works fine with MySQL:

SELECT concat(title,'/') FROM `socials` WHERE 1 

It Concat / to the selected title field.

However, when I try to do the following:

SELECT concat(*,'/') FROM `socials` WHERE 1 

It returns the follwoing Error:

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*,'/') FROM `socials` WHERE 1 LIMIT 0, 30' at line 1 

So is there any way to make such sql query to work with MySql

like image 366
SaidbakR Avatar asked Nov 25 '12 12:11

SaidbakR


People also ask

What is select concat?

SQL CONCAT function is used to concatenate two strings to form a single string. Try out the following example − SQL> SELECT CONCAT('FIRST ', 'SECOND'); +----------------------------+ | CONCAT('FIRST ', 'SECOND') | +----------------------------+ | FIRST SECOND | +----------------------------+ 1 row in set (0.00 sec)

How do I concatenate a string to a select query?

To append a string to another and return one result, use the || operator. This adds two strings from the left and right together and returns one result. If you use the name of the column, don't enclose it in quotes. However, in using a string value as a space or text, enclose it in quotes.

Does concat work in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.


2 Answers

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1 

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

like image 101
Ben Lee Avatar answered Oct 13 '22 09:10

Ben Lee


If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable 

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

like image 40
Joni Avatar answered Oct 13 '22 09:10

Joni