MySQL SELECT 语句:如何将变量的值显示到列标题中? [重复]

问题描述 投票:0回答:2

如何将变量的值放入 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 语句的结果作为列名?

mysql variables select title caption
2个回答
2
投票

您可以使用准备好的语句来完成它,如下所示:

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;

0
投票
SELECT @myMessage

UNION 

SELECT @myCaption

UNION 可以检索你想要的两列

© www.soinside.com 2019 - 2024. All rights reserved.