washoegary
washoegary

Reputation: 11

MySQL: alias column name question

Is it possible to alias a column name with the result of a simple SELECT query.

This doesn't work:

SELECT `hlevel1` AS (SELECT `level1` FROM `hierarchy_labels` LIMIT 1) FROM `hierarchy`;

Any Suggestions?

Upvotes: 1

Views: 1772

Answers (2)

Hal
Hal

Reputation: 591

You can't do this.

Aliases are used to rename a field or to name a calculated field.

If you simply want your results to be named 'hlevel1', you may want to try this:

SELECT level1 as hlevel1 FROM hierarchy_labels LIMIT 1

Upvotes: 3

David N. Jafferian
David N. Jafferian

Reputation: 466

Use a prepared statement.

SELECT `level1` INTO @x FROM `hierarchy_labels` LIMIT 1;
SET @s = CONCAT('SELECT `hlevel1` AS `', @x, '` FROM `hierarchy`');
PREPARE s FROM @s;
EXECUTE s;
DEALLOCATE PREPARE s;

Upvotes: 1

Related Questions