简体   繁体   中英

Mysql returning multiple column from same row in same in same table

Suppose I have table name "POST" which only contain "POST_ID" , I have a another table name post_meta , which also contain "POST_ID"(as foreign key) and two other column "meta_key" and "meta_value"

The structure of my tables are

Post Table :

post_ID
1
2

Meta Table :

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  

I want to create a such table like

post_id   suite_size  suite_number
1         1000         10
2         2000         20  

How can I do this ?

Try this:

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;

OR

If you want all posts whether they are not exists in post_meta table then use below query

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;

You need to use the pivot technique to show row as column to achieve this

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

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