I have written query using left join which joins 3 tables to get the data, they are:
Products:
product_id category_id master_category_id manufacturers_id product_name product_img product_des product_price product_status
17421 194 4,6,7,5 2504 prod_name image-1.jpg ---- ---- 1
master_categories:
master_category_id master_category_name original_image picture small thumb icon_img master_category_status
1 Dinnerware/Glassware cat-image1.jpg -- -- -- -- 1
manufacturers:
manufacturers_id manufacturers_name original_image picture small thumb manufacturers_status
1 CalMil Cal-Mil.png -- -- -- 1
My Query is:
select (Case When p.product_status = '0' Then 'Inactive'
When p.product_status = '1' Then 'Active'
Else 'Deleted' End) AS status,
m.manufacturers_name,
GROUP_CONCAT(mc.master_category_name) as master_category_name,
TRIM(p.product_name) as product_name,
p.product_status,p.product_id
from products p
left join manufacturers m
on p.manufacturers_id=m.manufacturers_id
left join master_categories mc
on find_in_set(mc.master_category_id,p.master_category_id)
where p.product_name!=''
GROUP BY p.product_name order by TRIM(p.product_name) ASC LIMIT 0,15
Each product has multiple master_categories which store their multiple master_category id's for 'master_category_id' column in 'products' table as shown in the 'products' table above.
My problem here is My query is returning a master_category_name even for product which doesn't have any 'master_category_id' ie, product is showing a master_category_name even if it doesn't have any master_category_id assigned and also product which has only 2 master_categories showing more than 2 categories .
Can anyone please help me What's wrong in my query. Thanks.
You need to do a group by on product_id column. If multiple products share the same name, it might be grouping those data and giving you incorrect result. Also find_in_set should be used with > 0 condition. Try this.
SELECT
(CASE
WHEN p.product_status = '0' THEN 'Inactive'
WHEN p.product_status = '1' THEN 'Active'
ELSE 'Deleted'
END) AS status,
m.manufacturers_name,
GROUP_CONCAT(mc.master_category_name) AS master_category_name,
TRIM(p.product_name) AS product_name,
p.product_status,
p.product_id
FROM
products p
LEFT JOIN
manufacturers m ON p.manufacturers_id = m.manufacturers_id
LEFT JOIN
master_categories mc ON FIND_IN_SET(mc.master_category_id,
p.master_category_id) > 0
WHERE
p.product_name != ''
GROUP BY p.product_id
ORDER BY TRIM(p.product_name) ASC
LIMIT 0 , 15
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.