MySQL concat() to create column names to be used in a query?(MySQL concat() 创建要在查询中使用的列名?)
问题描述
我想以列名的第一部分是字符串而第二部分是作为另一个查询结果的数字的方式连接列名.
I would like to concatenate column names in a way that the first part of the column name is a string and the second part is a number which is the result of another query.
例如:
SELECT CONCAT('column', mytable.mycolumn) FROM table ...
这可以以某种方式完成吗?这样它不会给我错误,但我没有得到预期的结果,而且连接似乎不起作用.
Can this be done in some way. This way it doesn't give me errors but I don't get the expected result and it seems the concatenation doesn't work.
推荐答案
我之前说过不能这样做,但我错了.我最终自己需要这样的东西,所以我环顾四周,发现 服务器端准备好的语句让您可以从字符串构建和执行任意 SQL 语句.
I previously said that this couldn't be done, but I was wrong. I ended up needing something like this myself so I looked around, and discovered that server-side prepared statements let you build and execute arbitrary SQL statements from strings.
这是我刚刚用来证明这个概念的一个例子:
Here is an example I just did to prove the concept:
set @query := (
select concat(
"select",
group_concat(concat("\n 1 as ", column_name) separator ','),
"\nfrom dual")
from information_schema.columns
where table_name = 'columns')
;
prepare s1 from @query
;
execute s1
;
deallocate prepare s1
;
这篇关于MySQL concat() 创建要在查询中使用的列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL concat() 创建要在查询中使用的列名?
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
