列名の最初の部分が文字列で、2 番目の部分が別のクエリの結果である数値になるように、列名を連結したいと思います。
例えば:
SELECT CONCAT('column', mytable.mycolumn) FROM table ...
これは何らかの方法で行うことができますか。この方法ではエラーは発生しませんが、期待した結果が得られず、連結が機能していないようです。
これはできないと前に言ったが、私は間違っていた。自分でこのようなものが必要になったので、周りを見回して、サーバー側のプリペアドステートメントを使用すると、文字列から任意のSQLステートメントを作成して実行できることを発見しました。
これは、概念を証明するために私が行った例です。
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
;
列の数が固定されている場合、非動的なアプローチは次のようになります。
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 ...
information_schemaを見ることをお勧めします。次のコードはテストされていませんが、理論的には動作するはずです。明らかにテーブル名を適切なテーブル名に置き換えるか、information_schema.tables にリンクし、where 句で table_type を使用します。
select concat('column', column_name) from information_schema.columns where table_name ='your table name'