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.
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.
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.
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.
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.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With