查询将键值表转换为人类可读的表?

时间:2014-11-13 20:28:56

标签: mysql sql

我确定之前已经询问过,但我不能在搜索中使用正确的关键字,因为我找不到任何内容。

我有一张如下表所示的表格:

+----+-----------+-----------+----------------+
| ID | entry_num | field_num | value          |
+----+-----------+-----------+----------------+
| 23 |        11 |         1 |  joe@gmail.com |
+----+-----------+-----------+----------------+
| 24 |        11 |         2 |             24 |
+----+-----------+-----------+----------------+
| 25 |        11 |         3 |           blue |
+----+-----------+-----------+----------------+
| 26 |        12 |         1 |    sue@aol.com |
+----+-----------+-----------+----------------+
| 27 |        12 |         2 |             32 |
+----+-----------+-----------+----------------+

我想构建一个 QUERY ,它会返回如下结果:

+-----------+---------------+-----+-------+
| entry_num | email         | age | color |
+-----------+---------------+-----+-------+
|        11 | joe@gmail.com | 24  | blue  |
+-----------+---------------+-----+-------+
|        12 | sue@aol.com   | 32  | NULL  |
+-----------+---------------+-----+-------+

我知道我需要手动将field_num转换为相应的column名称,但我有该列表(在纸面上,遗憾的是它不是另一个表)。

任何人都知道如何做到这一点?我之前已经解决了(问了,但正如我所说,我找不到问题!)而且我讨厌尝试重新发明轮子。

1 个答案:

答案 0 :(得分:1)

试试这个,也许它不是最好的解决方案,但它可以满足您的需求:

SELECT DISTINCT entry_num,(SELECT VALUE FROM your_tab t2 WHERE t2.entry_num = t1.entry_num
AND t2.field_num = 1)  AS email,
(SELECT VALUE FROM your_tab t2 WHERE t2.entry_num = t1.entry_num AND t2.field_num = 2)  AS age,
(SELECT VALUE FROM your_tab t2 WHERE t2.entry_num = t1.entry_num AND t2.field_num = 3) as color
 FROM your_tab t1