Sorry for the vague topic but I’m having a hard time explaining this. What I’m trying to do is fetching an ID representing a post which can be posted in different categories, and I want my post to belong to all three categories to match the criteria. The table looks like this
id category_id
1 3
1 4
1 8
What I wanna do is fetch an id that belongs to all 3 of these categories, but since they’re on different rows I can’t use
SELECT id FROM table WHERE category_id = '3' AND category_id = '4' AND category_id = '8';
This will of course return nothing at all, since no row matches that criteria. I’ve also tried with the WHERE IN clause
SELECT id from table WHERE category_id IN (3, 4, 8);
This returns any post in any of these categories, the post I want returned has to be in all three of these categories.
So the question becomes, is there any good way to look for an id that belongs to all three of these categories, or do I have to use the WHERE IN clause and see if I get 3 rows with the id 1, then I’ll know that it occured three times, therefor belongs to all three categories, seems like a bad solution.
Thanks in advance. I appreciate the help. 🙂
You could use
group_concatto get a comma separated string of your category id’s and check if that contains all the categories you’re filteringSELECT id, GROUP_CONCAT(t2.category_id) as categories
FROM table AS t1
INNER JOIN table AS t2 ON t1.id = t2.id
WHERE
FIND_IN_SET(‘3’, categories) IS NOT NULL AND
FIND_IN_SET(‘4’, categories) IS NOT NULL AND
FIND_IN_SET(‘8’, categories) IS NOT NULL
Update
The last query would not have worked, since it is a group function the value cannot be used in the
WHEREclause but can be used in theHAVINGclause.