SQL - 内部联接和列到行

时间:2014-02-17 14:02:25

标签: mysql sql

使用MySQL,我有两个类似于以下的表。两者实际上都有更多行和更多列,但为了便于阅读,我只提了几个

wp_ahm_files

ID | Field_A | Field_B | Field_C
--------------------------------
69 | ABC     | DEF     | GHI

wp_ahm_filemeta

此表中的pID是指上表的ID

ID | pID | Name    | Value
---------------------------------
25 | 69  | Version | 12345
26 | 69  | Expiry  | 29/08/1981

如何恢复结果集,例如

ID | Field_A | Field_B | Field_C | Version | Expiry
-------------------------------------------------------
69 | ABC     | DEF     | GHI     | 12345   | 29/08/1981

2 个答案:

答案 0 :(得分:2)

您应该能够加入wp_ahm_filemeta两次以获得结果:

select f.id,
  f.field_a,
  f.field_b,
  f.field_c,
  m1.value version,
  m2.value expiry
from wp_ahm_files f
left join wp_ahm_filemeta m1
  on f.id = m1.pid
  and m1.name = 'Version'
left join wp_ahm_filemeta m2
  on f.id = m2.pid
  and m2.name = 'Expiry';

SQL Fiddle with Demo。关键是在JOIN条件上放置一个过滤器,以返回具有所需特定name值的行。

您还可以使用带有CASE表达式的聚合函数将数据行转换为列:

select f.id,
  f.field_a,
  f.field_b,
  f.field_c,
  max(case when m.name = 'Version' then m.value end) version,
  max(case when m.name = 'Expiry' then m.value end) expiry
from wp_ahm_files f
left join wp_ahm_filemeta m
  on f.id = m.pid
group by f.id, f.field_a, f.field_b, f.field_c;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

这样的东西
  select a.*, version.value version, expiry.value expiry
  from a join 
  ( select * from b where name = 'Version' ) version
  on version.table_a_id = a.id
  join 
  ( select * from b where name = 'Expiry' ) expiry
  on expiry.table_a_id = a.id