Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : multiple column values as 1 comma-separated string?

Tags:

select

mysql

Suppose I have a select query like :

SELECT * FROM tablename

and in the table are columns : field1, field2 and field3

Does anyone know if it's possible to get a resultset with only 1 row with 1 field, with comma separated values of the columns, like this :

"fieldvalue1, fieldvalue2, fieldvalue3"

Problem is that I don't know the column names of the table in advance...

Another problem is that a prepared statement is not the way to go, since all this should be done from within a trigger, and MySQL doesn't allow dynamic cursors/selects inside a trigger.

like image 556
Dylan Avatar asked Feb 26 '23 11:02

Dylan


1 Answers

I have done some research and only came as far as GROUP_CONCATenating the column names correctly. But the problem is, that

SELECT (SELECT GROUP_CONCAT( cols.column_name) FROM (SELECT column_name FROM information_schema.columns WHERE table_name='test_table') as cols) FROM test_table

will return one and the same concatenated string containing the column names, once for each table row, instead of evaluating it as the column names for the outer select statement and returning the actual values.

From what I have read in all of the forums discussing this kind of question (and there were many), there is really no way of getting this to work without prepared statements.

I can only think of one other way to do this, and that would be having a dedicated column on each table, where you concatenate the individual column values on INSERT or UPDATE, so you can simply select this one field instead of the full set of fields.

like image 63
weltraumpirat Avatar answered Feb 27 '23 23:02

weltraumpirat