简体   繁体   中英

SQL - Inner Join and Columns to Rows

Using MySQL and I have two tables similar to the following. Both actually have more rows and more columns but for ease of reading, I've only put a few

wp_ahm_files

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

wp_ahm_filemeta

pID in this table refers to the ID of the table above

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

How do I bring back a resultset such as

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

You should be able to JOIN to your wp_ahm_filemeta twice to get the result:

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';

See SQL Fiddle with Demo . The key is to place a filter on the JOIN condition to return the rows with the specific name value you want.

You could also convert the rows of data into columns by using an aggregate function with a CASE expression:

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;

See SQL Fiddle with Demo

Something like

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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