Question

I would like to concatenate column names in a way that the first part of the column name is a string and the second part is a number which is the result of another query.

For example:

SELECT CONCAT('column', mytable.mycolumn) FROM table ...

Can this be done in some way. This way it doesn't give me errors but I don't get the expected result and it seems the concatenation doesn't work.

Was it helpful?

Solution

I previously said that this couldn't be done, but I was wrong. I ended up needing something like this myself so I looked around, and discovered that server-side prepared statements let you build and execute arbitrary SQL statements from strings.

Here is an example I just did to prove the concept:

set @query := (
  select concat(
    "select",
      group_concat(concat("\n  1 as ", column_name) separator ','),
    "\nfrom dual")
  from information_schema.columns
  where table_name = 'columns')
;
prepare s1 from @query
;
execute s1
;
deallocate prepare s1
;

OTHER TIPS

If the number of columns is fixed, then a non-dynamic approach could be:

select 
  case mytable.mycolumn
    when 1 then column1  -- or: when 'a' then columna
    when 2 then column2
    when ...
    else ...
  end as my_semi_dynamic_column
from ...

I don't believe you can do this with CONCAT() and CONCAT_WS(). I'd recommend using the langauge you are working with the create the field names. Doing it this way would be pretty scary, depending on where the data in the database came from.

I would suggest looking at information_schema. The following code is untested but should theoretically work. Obviously replace your table name with an appropriate table name or link to information_schema.tables and use the table_type in your where clause

select concat('column', column_name) from information_schema.columns where table_name ='your table name'

You can easily use following query:

SELECT group_concat( COLUMN_NAME) FROM information_schema.columns WHERE table_name ='your table name';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top