2

I want to covert the result row from the select query into a comma-separated string. I have table in which there are 153 columns. the select query is like as follow

SELECT * FROM mytable where id = 3

I want all the resulting 153 columns of a row in a comma-separated string. Is there any trick in MySql?

1

2 Answers 2

11

You can use GROUP_CONCAT function to do that.

SELECT GROUP_CONCAT(col1, col2,..coln) FROM my_table;

EDIT:

get all column names with following query and the substitute that in CONCAT_WS function::

SELECT GROUP_CONCAT(COLUMN_NAME) 
FROM information_schema.COLUMNS 
WHERE TABLE_NAME = 'my_table';

SELECT CONCAT_WS(',', col1, col2, ..., coln) 
FROM my_table;

or try:

SET @query1 = CONCAT('
        SELECT CONCAT_WS(",", ',(SELECT GROUP_CONCAT(COLUMN_NAME)
                                 FROM information_schema.COLUMNS
                                 WHERE TABLE_NAME = 'my_table'),')
        FROM    tablew_name'
        );
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

5 Comments

Group_concat() will give the results from multiple rows, not multiple comumns.
@Fluffeh - Yes exactly, I want columns of a single row comma separated (using where clause)
@hemu Nevermind, I misread the question. Thought you wanted all the columns per row in one field.
k...your solution seems to be working. I am trying this one - SELECT GROUP_CONCAT(COLUMN_NAME) INTO @cols FROM information_schema.COLUMNS WHERE TABLE_NAME = 'myTable'; SELECT CONCAT_WS(',', @cols) FROM myTable WHERE id = 3; but this is giving me comma seperated name of columns. not values...Any help ?
ya you need to copy past all those columns to CONCAT_WS function to make new query and don't forget to accept answer.
0

You can use the concat() function, but you will need to name each column as far as I know.

select concat(col1, ',', col2, ',', col3) from myTable where id=3

The only way that I know of to get all the columns of a table is SHOW COLUMNS FROM table and I guess you could include the results from this into your query but it isn't something that I have ever done before.

2 Comments

Yes that will work, but I am gonna write down this in trigger. So let's say after 2 months a new column will be added , I will need to edit the trigger code. That's why using column name is not recommended.
@hemu No worries, from the question, I wasn't sure about the level of knowledge you have. I answered the question as I saw it mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.