简体   繁体   中英

SQL Merge two equal column names with two different values into one row

I want to merge two equal column names (meta_value) with different values into a one row result instead of two.

SELECT t1.ID, t1.post_content AS product, t2.meta_value AS price
FROM wp_posts AS t1
INNER JOIN wp_postmeta AS t2 ON ( t1.id = t2.post_id ) 
WHERE t1.post_type =  'product'
LIMIT 0 , 30

Results in

ID      product      price
1973    product1     12.35
1973    product1     12.10

And I want it to look like this

ID      product      price      sell
1973    product1     12.35      12.10

The meta_key for price is _price and the meta_key for sell is _sell

It looks like you can use an aggregate function with a case statement to transform the data

SELECT t1.ID, 
   t1.post_content AS product, 
   max(case when meta_key = '_price' then t2.meta_value end) AS price, 
   max(case when meta_key = '_sell' then t2.meta_value end) AS sell
FROM wp_posts AS t1
INNER JOIN wp_postmeta AS t2 ON ( t1.id = t2.post_id ) 
WHERE t1.post_type =  'product'
GROUP BY t1.ID, t1.post_content
LIMIT 0 , 30

But it is not exactly clear based on your table structure, so you might also be able to use:

SELECT t1.ID, 
   t1.post_content AS product, 
   max(t2.meta_value) AS price, 
   min(t2.meta_value) AS sell
FROM wp_posts AS t1
INNER JOIN wp_postmeta AS t2 ON ( t1.id = t2.post_id ) 
WHERE t1.post_type =  'product'
GROUP BY t1.ID, t1.post_content
LIMIT 0 , 30
SELECT
  t1.ID,
  t1.post_content AS product,
  max(case when t2.meta_key='_price' then t2.meta_value end) AS price,
  max(case when t2.meta_key='_sell' then t2.meta_value end) AS sell
FROM wp_posts AS t1
     INNER JOIN wp_postmeta AS t2 ON ( t1.id = t2.post_id )
WHERE t1.post_type =  'product'
GROUP BY t1.ID, t1.post_content
LIMIT 0 , 30

Hope this helps you,

SELECT t1.ID, t1.post_content AS product,max(t2.meta_value) as price,min(t2.meta_value) as sell
FROM wp_posts AS t1
INNER JOIN wp_postmeta AS t2 ON ( t1.id = t2.post_id ) 
WHERE t1.post_type =  'product'
LIMIT 0 , 30

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