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

房东的猫 提交于 2019-11-27 08:07:24
Chris Vest

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 ...

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';
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!