ramesh
ramesh

Reputation: 4082

MySQL search with multiple category id

I got a talbe like this

category_table

cat_id   |   cat_name
---------+--------------
1        |  cat 1'
---------+--------------
2        |  cat 2
---------+--------------
3        |  cat 3
---------+--------------
4        |  cat 4
---------+--------------
5        |  cat 5

Another table called item table as follows

item_table

item_id   |   item_name    |  cat_id
----------+----------------+-----------
1         |  name of item  |  2
2         |  name of item  |  1
3         |  name of item  |  2
4         |  name of item  |  3
5         |  name of item  |  2
6         |  name of item  |  4

I have got the following query for select in item_table

SELECT * FROM item_table WHERE cat_id=2

I got a category id array like this

$cats=array("2","3","3");

My question is how to perform a "multiple category" search using the above mentioned array ? Means I want select all items with category id 2,3,4.

Upvotes: 0

Views: 1039

Answers (1)

Yash
Yash

Reputation: 1436

Use In Operator of MYSQL:

SELECT * FROM item_table WHERE cat_id IN(2,3,4)

If you want to get result with join of tables then you can use:

SELECT t1.item_id, t1.item_name, t1.cat_id, t2.cat_name 
FROM item_table t1 
INNER JOIN category_table t2 ON t1.cat_id = t2.cat_id
WHERE t1.cat_id IN(2,3,4)

Upvotes: 2

Related Questions