如何在子查询中使用主查询中的值

时间:2013-12-05 20:29:38

标签: mysql subquery

我试图运行一个基于其中一个主要查询值的子查询,但我总是得到0作为VALUE。 这是我的问题:

SELECT ID,(
SELECT COUNT( * ) 
    FROM  `post_meta` 
    WHERE  `post_id` 
    IN (
        SELECT  `ID` 
        FROM  `wp_posts` 
        WHERE  `post_title` = posts.ID
    )
) AS counter
FROM wp_posts;

如果我只运行带有id号而不是posts.ID的子查询,则返回一个好的值。

3 个答案:

答案 0 :(得分:1)

我相信在子查询中进行简单的连接会得到正确的COUNT:

SELECT posts.ID,
(
  SELECT COUNT(*) 
  FROM post_meta
  INNER JOIN wp_posts ON wp_posts.ID = post_meta.post_ID
  WHERE wp_posts.post_title = posts.ID  
) AS counter
FROM posts;

答案 1 :(得分:1)

Linger你打败了我,但如果我能猜出结构是什么样的话,我会建议完全忽略子查询。

SELECT ID, COUNT(*) AS count FROM wp_posts
INNER JOIN post_meta ON wp_posts.ID = post_meta.post_id
WHERE wp_posts.ID = post_title
GROUP BY ID

OR

SELECT COUNT(*) AS count FROM wp_posts 
INNER JOIN post_meta ON wp_posts.ID = post_meta.post_id
WHERE wp_posts.ID = post_title

答案 2 :(得分:1)

问题是通过为表提供一个自定义名称来解决的,所以我可以在进入两个层时使用它,这就是代码在更改后的样子:

SELECT ID,(
SELECT COUNT( * )
    FROM  `post_meta` 
    WHERE  `post_id` 
    IN (
        SELECT  `ID` 
        FROM  `wp_posts` 
        WHERE  `post_title` = my_posts.ID
    )
) AS counter
FROM wp_posts as my_posts;