mysql查询返回3列,我想从一列中获取值,并将其连接成逗号分隔的字符串

t9eec4r0  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(342)

我需要从meta\u value列中获取在相应的meta\u key列中有“shipping”的值,并将它们连接到一个逗号分隔的行中。
我有点不懂sql,所以请温柔一点。

我目前的问题是:

SELECT wp_postmeta.post_ID, wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.post_status 
FROM wp_postmeta 
CROSS JOIN wp_posts 
WHERE wp_postmeta.post_ID= wp_posts.ID 
  AND wp_posts.post_status LIKE 'wc-processing' 
  AND (wp_postmeta.meta_key LIKE '%shipping%' OR wp_postmeta.meta_key LIKE '_order_total')
qaxu7uf2

qaxu7uf21#

你可以用 GROUP_CONCAT 把弦连在一起。正如@kermit所指出的,您应该使用 INNER JOIN 不是一个 CROSS JOIN . 我想你应该把订单总额和发货明细分开,所以你也需要使用条件聚合。此查询应满足您的要求:

SELECT m.post_ID
     , GROUP_CONCAT(CASE WHEN m.meta_key LIKE '%shipping%' THEN m.meta_value END) AS shipping_info
     , MAX(CASE WHEN m.meta_key = '_order_total' THEN m.meta_value ELSE 0 END) AS order_total
FROM wp_postmeta m
INNER JOIN wp_posts p ON m.post_ID = p.ID 
WHERE p.post_status LIKE 'wc-processing' 
  AND (m.meta_key LIKE '%shipping%' OR m.meta_key LIKE '_order_total')
pbossiut

pbossiut2#

这样做应该比在SQLServer上更复杂一些,但也很简单

create table if not exists test(col1 varchar(10),col2 varchar(10), col3 varchar(10));
insert into test values("this","is","test");
select concat(col1,",",col2,",",col3) as csvCol from test

交付

csvCol
this,is,test
f4t66c6m

f4t66c6m3#

所以,这里是您的查询(注意我是如何编写的-我发现良好的sql格式有助于读取它):

SELECT  
    wp_postmeta.post_ID, 
    wp_postmeta.meta_key, 
    wp_postmeta.meta_value, 
    wp_posts.ID, 
    wp_posts.post_status 
FROM 
    wp_postmeta 
CROSS JOIN 
    wp_posts 
WHERE 
    wp_postmeta.post_ID = wp_posts.ID 
    AND wp_posts.post_status LIKE 'wc-processing' 
    AND (wp_postmeta.meta_key LIKE '%shipping%' OR wp_postmeta.meta_key LIKE '_order_total')

以下是我认为您需要的(您使用mysql concat函数):

Select
   concat(
        wp_postmeta.meta_key, ',',
        wp_postmeta.meta_value
    ) as formatted_row
FROM 
    wp_postmeta 
INNER JOIN 
    wp_posts 
ON
    wp_postmeta.post_ID = wp_posts.ID 
WHERE 
    wp_posts.post_status LIKE 'wc-processing' 
    AND (
           wp_postmeta.meta_key LIKE '%shipping%' 
           OR wp_postmeta.meta_key LIKE '_order_total'
        )

另请注意:单引号和双引号在不同的数据库中表示不同的内容。

相关问题