1

I want to display names for columns in another table like so :

select data.data1 as head.colHeader1, data.data2 as head.colHeader2 from DATA_TABLE data, HEADER_TABLE head where data.Key = header.Key and header.key = 'someUniqueKey'

the above query isn't correct - is it possible to use "dynamic" column names from another table? If so, what is the correct syntax?

neggenbe
  • 1,697
  • 2
  • 24
  • 62

2 Answers2

2

The answer is simple: It is not possible in SQL. Column aliases are constants. You would have to create the query dynamically to achieve what you want:

SET @column_alias1 := SELECT colHeader1 FROM HEADER_TABLE header WHERE header.key = 'someUniqueKey';
SET @column_alias2 := SELECT colHeader2 FROM HEADER_TABLE header WHERE header.key = 'someUniqueKey';
SET @query := CONCAT('select data.data1 as `', @column_alias1, '`, data.data2 AS `', @column_alias2, '` FROM DATA_TABLE data where data.Key = header.Key ');
PREPARE dynamic_statement FROM @query;
EXECUTE dynamic_statement;
A. Colonna
  • 852
  • 7
  • 10
0

As mentioned in the comment, the route you would have to go is setting the alias yourself such as:

select data.data1 as 'what you want', data.data2 as 'what you want' 
from DATA_TABLE data 
inner join HEADER_TABLE header where data.Key = header.Key and header.key = 'someUniqueKey'

also as a heads up you had HEADER_TABLE head and had header.Key so I changed it to HEADER_TABLE header

t..
  • 1,101
  • 1
  • 9
  • 22