I have 3 tables that look like this:
-
Table 1 (main table):
item_id (item_id, item_name) // item_id set to primary row1 (1, "item 1") row2 (2, "item 2") row3 (3, "item 3") -
Table 2 (linking table):
item_keywords (ikid, #item_id, #keyword_id) // ikid is set to primary row1 (1, 1, 1) row2 (2, 1, 2) row3 (3, 1, 3) row4 (4, 2, 1) row5 (5, 3, 1) -
Table 3:
keywords (keyword_id, keyword_name) // keyword_id is set to primary row1 (1, "key1") row2 (2, "key2") row3 (3, "key3") row4 (4, "key4") row5 (5, "key5")
I would like to make a query that returns all items that contain certain keywords AND also don’t contain some other keywords.
If you look at the table data above you can see that:
Item 1 contains keywords with ids: 1,2 and 3;
Item 2 contains keyword with id: 1
item 3 contains keyword_id =1
So I need a query that will return all items that contain key1 (keyword_id=1) and DON’T contain key3 (keyword_id=3). In this exmaple the query should return key2 (keyword_id=2), key3 (keyword_id=3).
Something like this:
SELECT a.*
FROM items a
JOIN item_keywords b ON b.item_id = a.item_id
WHERE b.keyword_id = 1
AND b.keyword_id != 3
But this doesn’t work properly because the query returns key1,key2 and key3. The answer should be: key2 and key3. What would be the simplest way of doing this?
Example of query working: