我正在尝试将每行中的key = value对分组到一个按ID分组的行中。
表1. wp_posts
键:ID - post_title
表2. wp_postmeta
键:post_id,wpcf-owner,wpcf-tel,wpcf-mob,wpcf-email ......
使用此查询,我获取所有信息,但是对于每个键,我得到单独的行。我需要的是一个数组,其中all由wp_posts.ID
组成一行SELECT wp_posts.ID, wp_posts.post_title, wp_postmeta.post_id, wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_type = 'accommodation' AND wp_postmeta.meta_key LIKE 'wpcf%'
ORDER BY hic13_posts.post_title
结果是:
ID | post_title | key value
------------------------------
1 | TITLE | wpcf-owner
1 | TITLE | wpcf-tel
1 | TITLE | wpcf-mob
1 | TITLE | wpcf-email
2 | TITLE | wpcf-owner
2 | TITLE | wpcf-tel
2 | TITLE | wpcf-mob
2 | TITLE | wpcf-email
...
我需要的是:
ID | post_title | key value | key value | key value | key value
-----------------------------------------------------------------
1 | TITLE | wpcf-owner | wpcf-tel | wpcf-mob | wpcf-email
2 | TITLE | wpcf-owner | wpcf-tel | wpcf-mob | wpcf-email
如果我按ID添加命令,那么我只从第二个表中获得一个键...
SELECT wp_posts.ID, wp_posts.post_title, wp_postmeta.post_id, wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_type = 'accommodation' AND wp_postmeta.meta_key LIKE 'wpcf%'
GROUP BY hic13_posts.ID
ORDER BY hic13_posts.post_title
我只得到这个
ID | post_title | key value
------------------------------
1 | TITLE | wpcf-owner
2 | TITLE | wpcf-tel
希望这一切都有道理:-)
谢谢!
答案 0 :(得分:1)
此类转换是 pivot ,但MySQL没有pivot函数,因此您需要使用带有CASE
表达式的聚合函数。:
SELECT p.ID,
p.post_title,
m.post_id,
max(case when m.meta_key = 'wpcf-owner' then m.meta_value end) as owner,
max(case when m.meta_key = 'wpcf-tel' then m.meta_value end) as tel,
max(case when m.meta_key = 'wpcf-mob' then m.meta_value end) as mob,
max(case when m.meta_key = 'wpcf-email' then m.meta_value end) as email
FROM wp_posts p
JOIN wp_postmeta m
ON p.ID = m.post_id
WHERE p.post_type = 'accommodation' AND m.meta_key LIKE 'wpcf%'
GROUP BY p.ID, p.post_title, m.post_id
ORDER BY p.post_title
编辑,如果要转换的meta_key
个项目数量未知,则可以使用预准备语句生成动态sql:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(CASE WHEN m.meta_key = ''',
meta_key,
''' THEN m.meta_value else null END) AS `',
meta_key, '`'
)
) INTO @sql
FROM wp_postmeta;
SET @sql
= CONCAT('SELECT p.ID,
p.post_title,
m.post_id, ', @sql, '
FROM wp_posts p
JOIN wp_postmeta m
ON p.ID = m.post_id
WHERE p.post_type = ''accommodation''
AND m.meta_key LIKE ''wpcf%''
GROUP BY p.ID, p.post_title, m.post_id
ORDER BY p.post_title');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;