【发布时间】:2018-04-01 16:34:08
【问题描述】:
我有两张桌子:
表 1:
ID Measurement_Name
1 Temperature
2 Humidity
表 2:
DateTime * ID * Value
2017-10-20 15:52:00 * 1 * 22,3
2017-10-20 15:51:00 * 1 * 22,1
2017-10-20 15:50:00 * 2 * 45
2017-10-20 14:52:00 * 1 * 22,3
现在我从表 2 中选择值
select DateTime , Value as 'temperature'
from Table 2
where ID = 1;
结果:
DateTime * temperature
2017-10-20 15:52:00 * 22,3
2017-10-20 15:51:00 * 22,1
2017-10-20 14:52:00 * 22,3
效果很好。但我想用表 1 中的文字“温度”代替文字“温度”。 我想要类似的东西
set @col_name := select Measurement_name from Table1 where ID = 1;`
我通过以下方式实现了这一点:
set @statement := CONCAT("select DateTime , Value as '",@col_name,"' from Table2 where ID = 1");
Prepare statement from @statement;
execute statement;`
但我更喜欢:
select DateTime , Value as @col_name
from Table2
where ID = 1;
但这会产生错误(服务器只是告诉我,查询附近有错误。
【问题讨论】:
-
使用准备语句是归档您想要的内容的唯一方法。MySQL 用户变量适用于可变数据,而不是像您尝试使用 MySQL 用户变量那样适用于可变 SQL。