Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL concat() to create column names to be used in a query?

Tags:

concat

mysql

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.

like image 405
markus Avatar asked Jun 12 '09 09:06

markus


People also ask

How do I concatenate a query in MySQL?

CONCAT() function in MySQL If the arguments include any binary strings, the result is a binary string. If a numeric argument is given then it is converted to its equivalent nonbinary string form. Syntax : CONCAT(str1, str2, ...)

How do you concatenate two columns in query?

Select two or more columns that you need to merge. To select more than one column contiguously or discontiguously, press Shift+Click or CTRL+Click on each subsequent column. The order of selection sets the order of the merged values. Select Transform > Merge Columns.

What does concat mean in MySQL?

Definition and Usage The CONCAT() function adds two or more expressions together.


2 Answers

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
;
like image 187
Chris Vest Avatar answered Sep 28 '22 02:09

Chris Vest


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 ...
like image 40
Arjan Avatar answered Sep 28 '22 02:09

Arjan