Mysql从同一行中的同一行返回多列

时间:2014-12-19 05:42:27

标签: mysql sql select group-by pivot

假设我的表名“POST”只包含“POST_ID”,我有另一个表名post_meta,它还包含“POST_ID”(作为外键)和另外两列“meta_key”和“meta_value”

我的表结构是

邮政表:

post_ID
1
2

元表:

meta_id      post_id        meta_key          meta_value 
1              1            suite_size        1000
2              1            suite_number      10 
3              2            suite_size        2000
4              2            suite_number      20  

我想创建一个像

这样的表
post_id   suite_size  suite_number
1         1000         10
2         2000         20  

我该怎么做?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT pm.post_ID,
       SUM(CASE WHEN pm.meta_key = 'suite_size' THEN pm.meta_value ELSE 0 END) as suite_size,
       SUM(CASE WHEN pm.meta_key = 'suite_number' THEN pm.meta_value ELSE 0 END) as suite_number
FROM post_meta pm 
GROUP BY pm.post_ID;

如果您想要post_meta表中的所有帖子是否不存在,请使用以下查询

SELECT p.post_ID,
       SUM(CASE WHEN pm.meta_key = 'suite_size' THEN pm.meta_value ELSE 0 END) as suite_size,
       SUM(CASE WHEN pm.meta_key = 'suite_number' THEN pm.meta_value ELSE 0 END) as suite_number
FROM post p
LEFT JOIN post_meta pm ON p.post_id = pm.post_ID
GROUP BY p.post_ID;

答案 1 :(得分:1)

您需要使用数据透视技术将行显示为列以实现此

select
p.post_ID,
max(case when pm.meta_key = 'suite_size' then pm.meta_value end) as `suite_size`,
max(case when pm.meta_key = 'suite_number' then pm.meta_value end) as `suite_number`
from post p
join post_meta pm on pm.post_id = p.post_ID
group by p.post_ID