Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stanhook's avatar

MySQL Query within a Query

Hi, I just need a little help, I am not the best at MySQL queries.

I have this query that returns and ID based on info I get from the URL:

SELECT wp_postmeta.post_id
FROM wp_postmeta
WHERE  wp_postmeta.meta_value = '5mt3807'

The ID that returns I need to use in this query:

SELECT wp_posts.ID, wp_posts.post_content, wp_posts.post_title, 
wp_posts.post_excerpt, wp_posts.post_name,
 wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
RIGHT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_type = 'm6_projects' AND 

wp_posts.ID = 'THIS IS THE ID FROM THE OTHER QUERY' 

 AND wp_postmeta.meta_value NOT LIKE 'field%'

How can I accomplish this?

Thanks, Stan

0 likes
3 replies
stanhook's avatar

I don't know if this is the best way but it works. I did this:

$id is from the URL

$postId = DB::connection('mysql_second')->table('wp_postmeta')
            ->where('wp_postmeta.meta_value',  $id)->value('post_id');

I then placed that into my other query:

WHERE wp_posts.post_type = 'm6_projects' AND wp_posts.ID = :postId 

Would that be the best way?

Jsanwo64's avatar
Jsanwo64
Best Answer
Level 11

Yes, your approach works well for the task you're trying to accomplish. By splitting the query and first fetching the post_id and then using it in the second query, you're effectively solving the problem. However, if you'd like to optimize it, you can combine both queries into a single query using a subquery. This can potentially improve performance by reducing the number of queries executed.

SELECT wp_posts.ID, wp_posts.post_content, wp_posts.post_title, 
       wp_posts.post_excerpt, wp_posts.post_name, 
       wp_postmeta.meta_key, wp_postmeta.meta_value
FROM wp_posts
RIGHT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_type = 'm6_projects'
  AND wp_posts.ID = (
        SELECT post_id 
        FROM wp_postmeta 
        WHERE wp_postmeta.meta_value = '5mt3807'
    )
  AND wp_postmeta.meta_value NOT LIKE 'field%'
stanhook's avatar

@jsanwo64 Awesome, that works, thanks!! I had tried something similar but gave up:

WHERE wp_posts.post_type = 'm6_projects'
  AND  (
        SELECT post_id 
        FROM wp_postmeta 
        WHERE wp_postmeta.meta_value = '5mt3807' AS postID
    )

With a few variations but gave up. Thanks for the help and increasing my knowledge!

1 like

Please or to participate in this conversation.