1

I am trying to do a manual query for WordPress postmeta table which would combine two types of postmeta into one with multiple columns by post_id.

This is the structure of table:

--------------------------------------------------------
meta_id | post_id | meta_key | meta_value
1 | 100 | _wp_attachment_metadata | a:6:{s:5:"width"}
2 | 100 | _thumbnail_id | 23
`

This is the result I am trying to achieve:

--------------------------------------------------------
post_id | _wp_attachment_metadata | _thumbnail_id
100 | a:6:{s:5:"width"} | 23
Rick James
80.7k5 gold badges52 silver badges119 bronze badges
asked Apr 25, 2019 at 15:52

1 Answer 1

1
SELECT t1.post_id, t1.meta_value, t2.meta_value
FROM postmeta t1, postmeta t2
WHERE t1.post_id = t2.post_id
 AND t1.meta_key = '_wp_attachment_metadata'
 AND t2.meta_key = '_thumbnail_id'

or

SELECT post_id, 
 MAX(CASE WHEN meta_key = '_wp_attachment_metadata' 
 THEN meta_value END), 
 MAX(CASE WHEN meta_key = '_thumbnail_id' 
 THEN meta_value END)
FROM postmeta 
GROUP BY post_id

PS. First query skips post_id, if it have no one (any) of meta-keys, second query gives NULL for according output field in such case.

answered Apr 25, 2019 at 18:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.