Search code examples
mysqlsqlwordpresspost-meta

Subquery returns more than 1 row with a Wordpress postmeta query


I am trying to pull data from a subsite's posts and postmeta tables:

SELECT xyz_8_posts.ID,

(select xyz_8_postmeta.meta_value
from xyz_8_postmeta
inner join xyz_8_posts
on xyz_8_postmeta.post_id = xyz_8_posts.ID
where xyz_8_postmeta.meta_key = 'presentation_title'
AND xyz_8_postmeta.post_id = xyz_8_posts.ID
) as 'Presentation Title'


FROM xyz_8_posts
WHERE xyz_8_posts.post_type = "presenters"

I'm getting a "Subquery returns more than 1 row" error. I don't understand why this is. If I replace xyz_8_posts.ID in the WHERE clause with an actual ID the query returns one title.


Solution

  • You have an extra JOIN where you just want a correlated subquery:

    SELECT p.ID,
          (select pm.meta_value
           from xyz_8_postmeta pm
           where pm.post_id = p.ID and
                 pm.meta_key = 'presentation_title'
          ) as Presentation_Title
    FROM xyz_8_posts p
    WHERE p.post_type = 'presenters'