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

前端 未结 5 612
走了就别回头了
走了就别回头了 2020-11-30 06:43

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.

5条回答
  •  醉话见心
    2020-11-30 07:37

    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
    ;
    

提交回复
热议问题