Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use value from main query in sub query

Tags:

mysql

subquery

Im trying to run a sub-query that based on one of the main query values but i always get 0 as VALUE. This is my query :

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;

if i run only the sub-query with id number instead of posts.ID it returns a good value.

like image 239
user2326568 Avatar asked Dec 05 '13 20:12

user2326568


People also ask

How can I use one query result in another?

Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.

Can we use in sub-query?

Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator. A subquery is a query within another query. The outer query is called as main query and inner query is called as subquery.

Can subquery be used in FROM clause in SQL?

From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.

How do I use subquery columns in main query?

A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.


2 Answers

I do believe a simple join in the sub query will get you the correct 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;
like image 92
Linger Avatar answered Sep 22 '22 23:09

Linger


The problem was fixed by giving the table a custom name so i can use it when im going in two layers this is how the code look after the change :

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;
like image 30
user2326568 Avatar answered Sep 23 '22 23:09

user2326568