2017-05-03 76 views
0

我有一个带有id的表格作为第一个字段和其他带有描述字段的字段。例如。查询以获取结果中的列名和值?

id | color | length | year | land | name 
--------------------------------------------------- 
3 | blue | long | 1988 | Netherlands | Jan 
4 | yellow | short ..etc. 

我想提出一个新表的每一行上以下字段:ID,字段名(从我的第一个表),该字段的值。所以像这样:

3 | color | blue 
3 | length | long 
3 | year | 1988 
3 | land | Netherlands 
3 | name | Jan 
4 | color | yellow 
4 | length | short 
etc. 

有没有人知道如何在查询中做到这一点? (或者在PHP脚本?)

感谢和亲切的问候,阿里

+0

列的数量是固定的,事先知道,对不对? –

回答

0

首先,您需要兼容的数据类型做你想做什么。这通常是一个字符串。

然后,你可以通过几种方式来做到这一点。也许在MySQL最简单的就是union all

select id, 'color' as which, color from t union all 
select id, 'length' as which, cast(length as char) from t union all 
. . .