0

我想将具有不同值的两个相等的列名(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

price 的 meta_key 是 _price,sell 的 meta_key 是 _sell

4

3 回答 3

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
于 2012-12-17T14:35:38.167 回答
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
于 2012-12-17T14:37:59.960 回答
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
于 2012-12-17T14:38:49.710 回答