首页 > 解决方案 > 如何使用 select 语句的结果作为列名?

问题描述

我想将 select 语句的结果用作另一个 select 语句中的列名。我还想删除所有内容,包括表名的最后一个“_”,以便我可以在 where 子句中使用剩余的字符。

select 
   voters.name, 
   id, 
   vote 
from tbl1_compiled_number
inner join voters
   on tbl1_compiled_number.id = voters.id;

按预期工作。

我现在想要的是将投票列标记为以下结果:

select 
   question
from votes
   where concat(left(loc,1),id)=number // 1st character of the loc column and the id column equals "number". This is the "number" portion from table_compiled_number table name.

结果是“鸡可以过马路”

我最终想要的是:

select 
   voter.name, 
   id, 
   vote as (select questions from voters where concat(left(loc,1),id) = number)
from tbl1_compiled_number
inner join voter
   on tbl1_compiled_number.id = voter.id;

结果应如下所示:

+------------+--------+-----------------------------------+
| name       | id     | Can chickens cross the road alone |
+------------+--------+-----------------------------------+
| Bugs Bunny | ABC123 | No                                |
| Daffy Duck | DEF456 | No                                |
| Spiderman  | GHI789 | Yes                               |
+------------+--------+-----------------------------------+

标签: mysqlcolumnname

解决方案


推荐阅读