33

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

SaidbakR
  • 13,303
  • 20
  • 101
  • 195

4 Answers4

49

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?

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • Thank you all, but the most distinguishable aspect of this answer to obtain it as correct, is showing how to achieve selecting the multiple fields. – SaidbakR Nov 25 '12 at 12:42
  • 1
    @sємsєм, you do it by listing them manually (or, if you are using an app, you can use SQL to read the columns, and then use your app to construct a query like above). – Ben Lee Nov 25 '12 at 12:45
27

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
2

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

Randell
  • 6,112
  • 6
  • 45
  • 70
rekire
  • 47,260
  • 30
  • 167
  • 264
1

You cannot do this on multiple fields. You can also look for this.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331