karim_fci
karim_fci

Reputation: 1242

mysql multiple join and retrieving only one record from two inner join table

I am in stuck in a query. Here is my current query.

SELECT products.product_id, products.product_title,
    package_category_products.PCP_id,
    product_images.PI_file_name
FROM package_category_products
LEFT JOIN products ON products.product_id = package_category_products.PCP_product_id

-- BEGIN MARKED CODE
LEFT JOIN product_inventories on product_inventories.PI_product_id = products.product_id
INNER JOIN product_images on product_images.PI_product_id = product_inventories.PI_product_id
    AND product_images.PI_color = product_inventories.PI_color_id
-- END MARKED CODE

WHERE PCP_package_id = 17
AND PCP_package_category_id = 3
AND product_status ='active'  

This query currently return redundant data. I want to use a sub query at the marked code to return only one record from this two table after joining. So that I will avoid redundant data and note that I need only one record for each product.

Upvotes: 1

Views: 76

Answers (1)

one angry researcher
one angry researcher

Reputation: 612

Replace "SELECT" by "SELECT DISTINCT":

SELECT DISTINCT a.product_id, a.product_title, d.PCP_id, c.PI_file_name

FROM package_category_products as d
LEFT JOIN products as a
ON a.product_id = d.PCP_product_id 

LEFT JOIN product_inventories as b on b.PI_product_id = a.product_id 

INNER JOIN product_images  as c
ON c.PI_product_id = b.PI_product_id AND c.PI_color = b.PI_color_id

WHERE PCP_package_id = 17 AND PCP_package_category_id = 3 AND product_status ='active'

Upvotes: 1

Related Questions