首先是查询
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
答案 0 :(得分:2)
@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;
根据您的测试数据,加上两个curlies(引用和反引号):
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';
答案 1 :(得分:1)
SELECT md.id, md.cat, m1.value AS context1, m2.value AS context2
FROM (
SELECT DISTINCT id, cat
FROM mytable
WHERE id = 1
) md
LEFT JOIN
mytable m1
ON m1.id = 1
AND m1.cat = md.cat
AND m1.context = 'context 1'
LEFT JOIN
mytable m2
ON m2.id = 1
AND m2.cat = md.cat
AND m2.context = 'context 2'
答案 2 :(得分:0)
SELECT t1.id, t1.cat, t1.value as 'Context 1', t2.value as 'Context 2'
FROM mytable t1, mytable t2
WHERE t1.id = t2.id AND t1.cat = t2.cat and t1.context = 'Context 1' and t2.context = 'Context 2'
如果每个ID / cat组合同时具有上下文1和上下文2,则有效。