如何将此表复制并粘贴到另一个表?

时间:2013-01-15 10:12:03

标签: php mysql pivot

我有一个具有这种结构的表

TABLE #1
---------------------------------------------------------------------------
meta_id | post_id |    meta_key    |               meta_value          |
---------------------------------------------------------------------------
1234         5      thumbnail_url      http://www.domain/thumb.jpg
1235         5      swf_url            http://www.domain/flash.swf
1236         5      description        This is a description.
1237         6      thumbnail_url      http://www.domain/thumb.jpg
1238         6      swf_url            http://www.domain/flash.swf
1239         6      description        This is a description.
---------------------------------------------------------------------------

和另一个具有此结构的表

TABLE #2
----------------------------------------------------
ID |   post_title   | thumbnail | swf | description
----------------------------------------------------
5     Awesome Title     NULL     NULL    NULL
6    Stack Over Flow    NULL     NULL    NULL 
----------------------------------------------------

我需要将表1中的元值复制并粘贴到表2 WHERE post_id = ID。

非常感谢有关查询外观的任何见解。

2 个答案:

答案 0 :(得分:2)

UPDATE Table2 t2
INNER JOIN
(
   SELECT
     post_id, 
     MAX(CASE WHEN meta_key = 'thumbnail_url' THEN meta_value END) AS 'thumbnail', 
     MAX(CASE WHEN meta_key = 'swf_url' THEN meta_value END) AS 'swf',
     MAX(CASE WHEN meta_key = 'description' THEN meta_value END) AS 'description'
   FROM Table1
   GROUP BY post_id
) t1 ON t1.post_id = t2.id
SET t2.thumbnail = t1.thumbnail,
    t2.swf       = t1.swf,
    t2.description = t1.description;

SQL Fiddle Demo

答案 1 :(得分:1)

这种类型的数据转换称为 pivot 。 MySQL没有透视功能,因此您将使用带有CASE表达式的聚合函数。

此过程将行值转换为列。要选择此格式的数据,您可以使用:

select post_id,
  max(case when meta_key = 'thumbnail_url' then meta_value end) thumbnail,
  max(case when meta_key = 'swf_url' then meta_value end) swf_url,
  max(case when meta_key = 'description' then meta_value end) description
from table1 
-- where post_id = 1
group by post_id;

然后到UPDATE table2:

update table2 t2
left join
(
  select post_id,
    max(case when meta_key = 'thumbnail_url' then meta_value end) thumbnail,
    max(case when meta_key = 'swf_url' then meta_value end) swf_url,
    max(case when meta_key = 'description' then meta_value end) description
  from table1 
  -- where post_id = 1
  group by post_id
) t1
  on t2.id = t1.post_id
set t2.thumbnail = t1.thumbnail,
    t2.swf = t1.swf_url,
    t2.description = t1.description;

请参阅SQL Fiddle with Demo