在WHERE子句中使用SELECT子查询不起作用

时间:2014-08-31 20:08:33

标签: mysql sql wordpress

我试图在WHERE子句中使用SELECT子查询的结果:

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

但是看起来MySQL并不知道parent_status列,错误是:

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

但是,如果您删除AND parent_status =' publish',则会返回结果,包括parent_status列:

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
....

查询的目标是在外部查询中获取post_parent ID,然后在子查询中获取父查询的post_status。这是WordPress,我只是在他们有父母并且父母被发布的情况下才尝试列出媒体附件。

尝试将SELECT子查询与WHERE子句一起使用时,我可能会做一些根本性的错误。任何提示赞赏。

1 个答案:

答案 0 :(得分:2)

您不能在where子句中使用列别名。你有几个选择。在这种情况下最好的是使用允许having子句中的逻辑的MySQL扩展。子查询中也存在逻辑问题。我想你的意思是:

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;