0

我正在尝试将每个在其行上的键 = 值对分组到按 ID 分组的一行中。

表 1. wp_posts
键:ID - post_title

表 2. wp_postmeta
键:post_id、wpcf-owner、wpcf-tel、wpcf-mob、wpcf-email...

使用这个查询,我得到了所有信息,但是对于每个键,我得到单独的行。我需要的是一个数组,其中所有内容都在一行中,按 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 

希望这一切都有意义:-)
谢谢!

4

1 回答 1

1

这种类型的转换是枢轴,但 MySQL 没有枢轴函数,因此您需要使用带有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;
于 2013-03-28T20:23:08.873 回答