【问题标题】:mysql alias name from variable来自变量的mysql别名
【发布时间】: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。

标签: mysql alias literals


【解决方案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 

【讨论】:

  • 在使用JOIN时,我可以将测量名称作为表格中的单元格获取,但我希望将其作为表格的标题。
    DateTime * ID * Value * CONCAT (...)<br/> 2017-10-20 15:52:00 * 1 * 22,3 * temperature 1 <br/> 2017-10-20 15:51:00 * 1 * 22,1 * temperature 1 <br/> 2017-10-20 14:52:00 * 1 * 22,3 * temperature 1<br/>
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2016-04-28
  • 2018-02-15
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多