-4

I HAVE TABLE

TABLE CATEGORY
id | name | parent
1 | gadget | 0
2 | phone | 1
3 | laptop | 1
....

TABLE PRODUCT
id | name | cat
1 | post 1 | 2
2 | post 2 | 2
3 | post 3 | 3
....

i want to get product by category and subcategory

Display all product in gadget category

How i can do that ?

GMB
  • 216,147
  • 25
  • 84
  • 135

2 Answers2

1

With just one level of parent/child relationship (as shown in your sample data), you can self-join the category table:

select p.*, c.name, c1.name
from product p
inner join category c on c.id = p.cat
left join category c1 on c1.id = c.parent
GMB
  • 216,147
  • 25
  • 84
  • 135
0

the simple way, use double query

SELECT A.* FROM PRODUCT A
INNER JOIN CATEGORY B ON A.CAT = B.ID
WHERE B.ID = (SELECT ID FROM CATEGORY WHERE NAME = 'gadget') 
OR B.PARENT= (SELECT ID FROM CATEGORY WHERE NAME = 'gadget')
Habibillah
  • 27,347
  • 5
  • 36
  • 56