I have stucked with a situation, where i have to show posts on check and uncheck of the terms.
The posts having terms assigned. I have terms ‘Area’ and ‘Cuisines’ now i have to select the post which has the area ‘XYZ’ and cuisine ‘ABC’.
The query i have tried :-
SELECT p.ID, p.post_title
FROM wp_posts p
LEFT JOIN `wp_term_relationships` t
ON p.ID = t.object_id
LEFT JOIN `wp_term_taxonomy` tt
ON t.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.term_id IN (".$area.")
OR tt.term_id IN (".$cuis.")
GROUP BY t.object_id
HAVING COUNT( t.term_taxonomy_id ) = 2
LIMIT 0,7
And the Structure of the wp_term_taxonomy is shown here :-
The problem is the single table and single column and apply the AND operator between the values.
wp_term_relationship
object_id | wp_term_taxonomy_id | term_order
==============================================
134 | 36 | 0
______________________________________________
135 | 36 | 0
wp_posts
ID | post_title |
==================================
1 | Hello world! |
__________________________________
2 | Test |
wp_term_taxnomy
term_taxonomy_id term_id taxonomy description parent count
=============================================================================
1 1 category ------ 0 2
Suppose, we have 3 tables:
Exactly the structure, that you have.
Content:
And we need to select values from test1 table, that have rows in test1_to_test2 with (test2_id = 1) AND (test2_id = 2). So, we want this:
To do it we split the task into 2 subtasks:
1.Select
test1_id
from test1_to_test2, that has both rows present:2.Select the appropriate rows from test1, using the subquery and IN operator (it’s the SQL, that we need):
We get what we need:
Use the same approach with your tables, and you’ll get the posts which have the area ‘XYZ’ and cuisine ‘ABC’.
Your best bet is to do two joins, one for each term:
Also, you can change the
left join
s toinner join
s — which thewhere
clause does anyway. Theleft join
s would be useful for “or” conditions rather than “and” conditions.