I have 3 tables.
- Tour Table (optional)
- Tour Tag Relation Table (optional_tag_rel)
- Tour Theme Relation Table (optional_theme_rel)
A tour can have multiple tags and multiple themes. So I what to write and sql statement to find specified tours. For example find tours where tag id = 10 and 15 and theme id = 36 and 45.
SELECT DISTINCT (t1.id) FROM optional AS t1
LEFT JOIN optional_theme_rel as t3 ON t3.tour_id = t1.id AND (t3.theme_id =36 OR t3.theme_id =45)
LEFT JOIN optional_tag_rel as t2 ON t2.tour_id = t1.id AND (t2.tag_id = 10 OR t2.tag_id =15)
GROUP BY optional.id
These statement gets all records whose theme id = 36 or 45, but I need to use AND statement but when I use AND instead of OR, it shows no record. There has to be different way of doing this on sql but I dont know much about it.
If I understand correctly that you want tours that have both themes (with theme_id =36 and 45) and both tags (with tag_id=10 and 15), then you neither need the
GROUP BYnor theDISTINCT.But one way to do this is to join twice to each one of the secondary tables:
Another way to get same results is: