I'm having a little trouble figuring out a query.
I have three tables: widgets, categories, and widgetsCategories (which records which widgets belong to which categories, in a many-to-many relationship). We can ignore the categories table for this discussion - all we need are widgets and widgetsCategories.
Some example data:
//widgets:
widgetId title
1 Hammer
2 Saw
//categories:
categoryId title
1 Tools
2 Green Things
//widgetsCategories:
widgetCategoryId widgetId categoryId
1 1 1
2 2 1
3 1 2
So both the hammer and saw are tools, but only the hammer is a green thing
It's easy enough to find all the widgets for a given category, or all the categories for a given widget, but what about trying to find all the widgets that belong to several/all specified categories? In other words, I want to select all widgets that are both tools AND green things.
I tried:
SELECT widgets.* from widgets, widgetsCategories WHERE widgets.widgetId=widgetCategories.widgetId AND widgetCategories.categoryId=1 AND widgetCategories.categoryId=2
but obviously that doesn't work - I get nothing.
What's the proper way to do this sort of query? Do I need to do multiple queries or is there a straightforward way to do this?