SQL query to select posts from multiple categories

I have built a query to select posts within a category. Works fine.
But when I choose to add a secondary filter to exclude a category, the query return the same result set, as if the secondary category filter is being ignored.

In the following the query should select all posts in category 7 and exclude those in category 10:

Read More
$querystr = "SELECT * FROM $wpdb->posts 
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  

WHERE ($wpdb->term_taxonomy.term_id = 7
   AND $wpdb->term_taxonomy.term_id <> 10  
   AND $wpdb->term_taxonomy.taxonomy = 'category'   
   AND $wpdb->posts.post_type = 'post'  
   AND $wpdb->posts.post_status = 'publish')";

Can someone help?

Related posts

Leave a Reply

1 comment

  1. I would use the built in API like Rarst mentioned. You could do something like this:

    $just_seven = new WP_Query(
      array(
        'category__in' => array( 7 ),
        'category__not_in' => array( 10 )
      )
    );
    

    You would then have those items in $just_seven->posts.

    However, if you MUST use a direct SQL statement, I’d suggest using INNER JOIN instead of LEFT JOIN.