我将数据存储在mySQL数据库中,格式如下:
+------------+------------+-----------+
| id | field | value |
+============+============+===========+
| 1 | first | Bob |
+------------+------------+-----------+
| 1 | last | Smith |
+------------+------------+-----------+
| 2 | first | Jim |
+------------+------------+-----------+
| 2 | last | Jones |
+------------+------------+-----------+
我希望它返回如下:
+------------+------------+-----------+
| id | first | last |
+============+============+===========+
| 1 | Bob | Smith |
+------------+------------+-----------+
| 2 | Jim | Jones |
+------------+------------+-----------+
我知道这似乎是一种存储数据的愚蠢方式,但它只是我真正拥有的一个简单例子。该表格采用WordPress插件格式化,我希望无需重写插件即可使用。
从我读过的内容来看,我不能将PIVOT与mySql一起使用。是否有类似于PIVOT的东西,我可以用来达到我想要的目的?
答案 0 :(得分:2)
尝试此透视查询:
SELECT id,
MAX(CASE WHEN field = 'first' THEN value ELSE NULL END) AS first,
MAX(CASE WHEN field = 'last' THEN value ELSE NULL END) AS last
FROM yourTable
GROUP BY id
请按照以下链接查看正在运行的演示:
答案 1 :(得分:1)
试试这个;)
select
id,
max(if(field='first', value, null)) as first,
max(if(field='last', value, null)) as last
from yourtable
group by id