您好我有一张现有的桌子
post_meta
----------------------------------------------------------------
| meta_id | post_id | meta_key | meta_value |
----------------------------------------------------------------
| 1 | 1 | field1 | John Doe |
| 2 | 1 | field2 | jonedoe@gmail.com |
| 3 | 1 | field3 | 099999999 |
| 4 | 2 | field1 | Err ManMa |
| 5 | 2 | field2 | errmanma@gmail.com |
| 6 | 2 | field3 | 09231412312 |
----------------------------------------------------------------
如何创建或格式化我的post_meta表?
----------------------------------------------------------------
| meta_id | field1 | field2 | field3 |
----------------------------------------------------------------
| 1 | John Doe | jonedoe@gmail.com | 099999999 |
| 2 | Err ManMa | errmanma@gmail.com | 09231412312 |
----------------------------------------------------------------
感谢您的帮助
答案 0 :(得分:1)
我认为您的结果列应该是post_id, field1, field2, field3
,然后这是表格枢轴问题,请尝试以下方法:
select
post_id,
max(case when meta_key = 'field1' then meta_value end) as field1,
max(case when meta_key = 'field2' then meta_value end) as field2,
max(case when meta_key = 'field3' then meta_value end) as field3
from post_meta
-- where meta_key in ('field1', 'field2', 'field3')
group by post_id
-- having coalesce(field1, field2, field3) is not null