gpt4 book ai didi

mysql - 我们可以使用 sql 数据字段作为列名吗?

转载 作者:行者123 更新时间:2023-11-29 05:43:26 24 4
gpt4 key购买 nike

先查询

SELECT * FROM mytable WHERE id='1'

例如给我一定数量的行

id             |       context      |      cat     |    value
1 Context 1 1 value 1
1 Context 2 1 value 2
1 Context 1 2 value 3
1 Context 2 2 value 4

现在我的问题不是以这种方式接收结果我希望它是这样的

id      |   cat    |    Context 1     |  Context 2   
1 1 value 1 value 2
1 2 value 3 value 4

最佳答案

@updated - 请参阅代码块 3 (MySQL) 中的注释 #,它仅用于从控制台或 HeidiSQL 进行调试

您正在寻找的东西称为旋转。您没有说明这是在什么 DBMS 上,但是对于 SQL Server,请在联机丛书中查找 PIVOT 运算符 - 如果类别是固定的,它可能会起作用。如果没有,那么你需要动态 sql,比如

declare @sql nvarchar(max);

-- generate the column names
select @sql = coalesce(@sql + ',', '') + QuoteName(context)
from (select distinct context from mytable) T;

-- replace the column names into the generic PIVOT form
set @sql = REPLACE('
select id, cat, :columns:
from (select id, cat, context, value From mytable) p
pivot (max(value) for context in (:columns:)) pv',
':columns:', @sql)

-- execute for the results
exec (@sql)

测试数据

create table mytable (id int, context varchar(10), cat int, value varchar(20))
insert mytable select 1 ,'Context 1', 1 ,'value 1'
insert mytable select 1 ,'Context 2', 1 ,'value 2'
insert mytable select 1 ,'Context 1', 2 ,'value 3'
insert mytable select 1 ,'Context 2', 2 ,'value 4'

以上是针对 SQL Server 的。对于 MySQL,请改用它,它遵循相同的技术。

SELECT @sql := NULL;
SELECT @sql := group_concat(
'max(case when context=''',
replace(context,'''',''''''),
''' then value end) `',
replace(context,'`','``'),
'`')
from (select distinct context from mytable) T;
SELECT @sql := concat(
'select id, cat,',
@sql,
' from mytable group by id, cat');
# SELECT @sql; # commented out, PHP sees this as the first result
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

根据您的测试数据,加上两个 curl (引号和反引号):

create table mytable (id int, context varchar(10), cat int, value varchar(20));
insert mytable select 1 ,'Context 1', 1 ,'value 1';
insert mytable select 1 ,'Context 2', 1 ,'value 2';
insert mytable select 1 ,'Context 1', 2 ,'value 3';
insert mytable select 1 ,'Context 2', 2 ,'value 4';
insert mytable select 1 ,'Context''3', 1 ,'quote';
insert mytable select 1 ,'Context`4', 2 ,'backquote';

关于mysql - 我们可以使用 sql 数据字段作为列名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4680046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com