Using SELECT subquery in WHERE clause not working

I’m trying to use the result of a SELECT subquery in my WHERE clause:

SELECT 
ID,
post_parent as parent,
post_status,
(SELECT post_status as p FROM wp_posts WHERE ID = parent) as parent_status
FROM wp_posts 
WHERE post_type = 'attachment' 
AND post_status = 'inherit' 
AND post_parent != 0 
AND parent_status = 'publish'
ORDER BY post_date DESC

But it doesn’t seem like MySQL is aware of the parent_status column, the error is:

Read More
#1054 - Unknown column 'parent_status' in 'where clause'

However, if you remove AND parent_status = ‘publish’, you get the results back including the parent_status column:

ID      parent  post_status parent_status
1908    1904    inherit     publish
1907    1904    inherit     publish
1906    1904    inherit     publish
1905    1904    inherit     publish
1902    1900    inherit     publish
....

The goal of the query is to to grab the post_parent ID in the outer query, and then in the subquery grab the post_status of the parent. This is WordPress and I’m trying to list media attachments only if they have a parent and that parent is published.

I may be doing something fundamentally wrong with trying to use the SELECT subquery with the WHERE clause. Any tips appreciated.

Related posts

Leave a Reply

1 comment

  1. You cannot use a column alias in a where clause. You have several options. The best in this case is to use the MySQL extension that allows the logic in the having clause. You also have a logic problem in the subquery. I think you mean:

    SELECT ID, post_parent as parent, post_status,
           (SELECT post_status FROM wp_posts wp2 WHERE wp2.ID = wp.post_parent) as parent_status
    FROM wp_posts wp
    WHERE post_type = 'attachment'  AND post_status = 'inherit'  AND post_parent <> 0 
    HAVING parent_status = 'publish'
    ORDER BY post_date DESC;