mysql使用从数据库读取的列别名

iqjalb3h  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(345)

我想在另一个表中显示列的名称,如下所示:

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'

上面的查询不正确-是否可以使用其他表中的“动态”列名?如果是,正确的语法是什么?

vuktfyat

vuktfyat1#

如注解中所述,您必须自行设置别名,例如:

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'

作为一个提醒你
HEADER_TABLE head 而且有 header.Key 所以我把它改成了 HEADER_TABLE header

3mpgtkmj

3mpgtkmj2#

答案很简单:这在sql中是不可能的。列别名是常量。您必须动态创建查询以实现所需的功能:

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;

相关问题