如何将变量的值放入 SELECT 语句的 COLUMN 标题中,如下所示:
SET @myCaption := "This is my message:";
SET @myMessage := "Hello everyone!";
SELECT @myMessage /* as @myCaption */ ;
我想看到这个结果:
+---------------------+
| This is my message: |
+---------------------+
| Hello everyone! |
+---------------------+
但遗憾的是,我得到的是:
+-----------------+
| @myMessage |
+-----------------+
| Hello everyone! |
+-----------------+
使用 SELECT ... AS ... AS ... 不允许使用变量
– 列名可以有注释——是否有办法在列标题中显示这样的注释??
– 这没有帮助: 如何使用 select 语句的结果作为列名?
您可以使用准备好的语句来完成它,如下所示:
SET @myCaption := "This is my message:";
SET @myMessage := "Hello everyone!";
SET @sql = concat('SELECT "', @myMessage, '" AS "', @myCaption,'"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT @myMessage
UNION
SELECT @myCaption
UNION 可以检索你想要的两列