繁体   English   中英

SQL select 组在不同的列

[英]SQL select group on different column

有一个如下表:

meta_id post_id 元密钥 元值
000001 1 名称1 山姆
000002 1 电话1 12345678
000003 1 名称2 杰基
000004 1 电话2 23456789
000005 2 名称1 大卫
000006 2 电话1 11111111
000007 2 名称2 玛丽
000008 2 电话2 22222222

并希望结果是:

post_id 名称1 电话1 名称2 电话2
1 山姆 12345678 杰基 23456789
2 大卫 11111111 玛丽 22222222

(在 WordPress 数据库上使用 MySQL)

您需要 pivot 您在组中的行。

select post_id,
max(case when meta_key = 'name1' then meta_value end) name1,
max(case when meta_key = 'tel1' then meta_value end) tel1,
max(case when meta_key = 'name2' then meta_value end) name2,
max(case when meta_key = 'tel2' then meta_value end) tel2
from tbl
group by post_id

看看这个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM