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.
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, ...)
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.
Definition and Usage The CONCAT() function adds two or more expressions together.
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
;
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With