i have a category tabale
parent_cat cat_id title
0 1 fruit
0 2 vehicle
0 3 goods
1 4 sour
1 5 sweet
1 6 mixed
2 7 sedan
2 8 hatchback
2 9 car
and product table
offer_name parent_cat sub_cat
mango 1 4,6
maruti 2 7,8,9
apple 1 5,4
i want to join the table according the requested get parameter if ?title=fruit then i will get mango,apple and my sql query is
SELECT category.cat_id,category.title,product.parent_cat,product.offer_name
FROM category, product
WHERE category.cat_id=product.parent_cat
AND category.title='fruit' --requested get variable
output is : cat_id title parent_cat offer_name
1 fruit 1 mango
1 fruit 1 apple
if ?title=sour then i will get mango,apple and my sql query is
SELECT * FROM product WHERE CONCAT(',' , sub_cat , ',') LIKE '%,4,%'
output is : offer_name parent_cat sub_cat
mango 1 4,6
apple 1 4,5
my question is how to convert sour which id is 4 in place of '%,4,%' .so that i can put the get variable over there.how to join like 1st mysql query
if a product belongs to multiple categories you should have multiple rows in your table. it`sa many to many relationship. and your sql should be SELECT * FROM product WHERE sub_cat in ( ... )
The answer is: you can't.
MySQL cannot deal with comma separated lists. You basically have two choices:
Basically get the cat_id
first and then do the second query as in your example. But then you don't avoid the LIKE '%,4,%'
.
As mentioned by user3642242 you have a many-to-many-relationship. Usually in SQL you would use another relationship table in this case. So you would have a category
, product
and category_product_relationship
table. Your category_product_relationship
table would then look like this:
category_id product_id
1 1
1 3
2 2
... ...
It means that the product table needs an index, which is a good idea anyway since SQL loves Primary Keys and is super fast with them.
You would then do a JOIN
to query your products like so:
SELECT *
FROM category c
JOIN category_product_relationship r ON r.category_id = c.cat_id
JOIN product p ON p.id = r.product_id
WHERE c.title = 'sour'
(c, r and p are aliases)
You can then remove the parent_cat
and sub_cat
columns from your product
table and handle all of that through the relationship table.
As others have suggested you should consider redesigning your database in a proper relational way. But it is possible to get what you are looking for with the following query:
SELECT offer_name, parent_cat, sub_cat FROM product JOIN
(SELECT cat_id FROM category WHERE title = 'sour') AS temp ON
CONCAT(',',sub_cat,',') LIKE CONCAT('%,',temp.cat_id,',%')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.