2017-01-30 35 views
1

我想请求帮助。我试图将多行组合成多行 - 列。 这里的表想组:MySQL组行信息列基于一个表内的列值

+----+------+--------+--------+-------+ | id | type | index1 | index2 | value | +----+------+--------+--------+-------+ | 33 | v1 | 1 | 8 | 1a | | 33 | v1 | 2 | 6 | 1b | | 33 | v1 | 3 | 3 | 1c | | 33 | v2 | | 3 | 2x | | 33 | v2 | | 8 | 2y | | 33 | v2 | | 6 | 2z | | 34 | v1 | 1 | 5 | 1ass | | 34 | v1 | 2 | 3 | 1bss | | 34 | v1 | 3 | 4 | 1css | | 34 | v2 | | 3 | 2xss | | 34 | v2 | | 4 | 2yss | | 34 | v2 | | 5 | 2zss | +----+------+--------+--------+-------+

索引1用来保持索引2的秩序,它与V2类型值连接。

这是结果应该什么样子:

+----+--------+--------+------+------+ | id | index1 | index2 | v1 | v2 | +----+--------+--------+------+------+ | 33 | 1 | 8 | 1a | 2y | | 33 | 2 | 6 | 1b | 2z | | 33 | 3 | 3 | 1c | 2x | | 34 | 1 | 5 | 1ass | 2zss | | 34 | 2 | 3 | 1bss | 2xss | | 34 | 3 | 4 | 1css | 2yss | +----+--------+--------+------+------+

感谢, T.

+0

的可能的复制[MySQL的数据透视表] (http://stackoverflow.com/questions/7674786/mysql-pivot-table) –

回答

0

这是你想要的:

select 
    t1.id, 
    t1.index1, 
    t1.index2, 
    t1.value v1 
    t2.value v2 
from (
    select * 
    from your_table 
    where type = 'v1' 
) t1 left join (
    select * 
    from your_table 
    where type = 'v2' 
) t2 on t1.id = t2.id 
and t1.index2 = t2.index2; 
+0

这工作,但我怎么能添加更多的类型? –

+0

好了:)它在我的表中有不正确的值。只需添加额外的JOIN,它就像预期的那样工作。谢谢! –

相关问题