0

I need to select a value from a column in the table as a name of the another column in mysql

for ex :: select column AS (select column from table where id = 1) from table;

it give me a syntax error .. How can I use select statement inside AS Function

Actually I need to set a value from a column as a name to another column using AS Function in mysql

MatBailie
  • 83,401
  • 18
  • 103
  • 137
  • 1
    `AS` is used the other way around; `expression AS name`. Even so, I'm not clear on what you're ***trying*** to do. Please edit your question to include an example; demonstration data for the contents of your table ***and*** the results you'd want from that demonstration data. [mre] – MatBailie Feb 08 '23 at 13:09
  • Again, it's not clear what you are asking but it's likely to require generating dynamic SQL in a script/code/procedure – NickW Feb 08 '23 at 14:08
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 08 '23 at 18:02
  • This question is already addressed in SO before. Check [StackOverflow](https://stackoverflow.com/questions/4428761/mysql-field-name-from-variable) – mrrobot.viewsource Feb 09 '23 at 11:15

2 Answers2

1

The answer is simple: It is not possible in SQL. Column aliases are constants.

Jonathan Delean
  • 1,011
  • 1
  • 8
  • 25
1

You can't do this in a single query. All identifiers must be fixed in the query at the time it is parsed, which is before the query begins reading data. This includes column names and column aliases. The names or aliases of columns cannot be set at runtime based on data read during the query.

But you can do what you want in two queries.

  1. Query to get the column alias name you want to use. This returns a string.
  2. Use that string as you format the second query. Then the column alias will be fixed in that second query by the time you prepare it.
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828