SQL将具有两个不同值的两个相等列名称合并为一行

时间:2012-12-17 14:30:22

标签: mysql sql wordpress

我想将两个具有不同值的相等列名(meta_value)合并为一行结果而不是两行。

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

结果

ID      product      price
1973    product1     12.35
1973    product1     12.10

我希望它看起来像这样

ID      product      price      sell
1973    product1     12.35      12.10

价格的meta_key是_price,卖出的meta_key是_sell

3 个答案:

答案 0 :(得分:3)

看起来你可以使用带有case语句的聚合函数来转换数据

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

但根据您的表结构并不完全清楚,因此您也可以使用:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

希望这会对你有所帮助,

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