I have a problem when doing a SQL query in WordPress, I would like to have each Post ID in a single row with the meta_key columns, but I get several uneven records.
SELECT P.ID,
IF(PM.meta_key = 'nombrem', PM.meta_value, NULL) AS nombrem,
IF(PM.meta_key = 'generom', PM.meta_value, NULL) AS generom,
IF(PM.meta_key = 'tiempom', PM.meta_value, NULL) AS tiempom,
IF(PM.meta_key = 'urlm', PM.meta_value, NULL) AS urlm,
IF(PM.meta_key = 'imagenm', PM.meta_value, NULL) AS imagenm
FROM K1nG_posts AS P
LEFT JOIN K1nG_postmeta AS PM ON ( P.ID = PM.post_id )
WHERE P.post_type = 'post'
AND (P.post_status = 'publish' OR P.post_status = 'private') ORDER BY P.post_date DESC
By placing the above code I get the following in phpmyadmin, I want a single post ID to have each meta_value value in a non-diagonal horizontal column as shown.
2
Answers
You seeem to be looking for conditional aggregation. For this, you would need to add a
GROUP BY
clause and surround your conditional expressions with an aggregate function:Group the data by P.id and max the ifs out
like