来自变量的 MySQL 别名



我有两个表:

表 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;

但这会产生一个错误(服务器只是告诉我,查询附近有一个错误。

JOIN 呢?

SELECT t1.*, t2,*, CONCAT(t1.Measurement_Name,t2.value)
FROM Table1 t1
JOIN Table2 t2
  ON t1.ID = t2.ID
WHERE t1.ID = 1 

最新更新