简体   繁体   中英

Changing mysql query to return always results

I have this query which checks for related(similar) to the shown one products and if there any it will show them. How to change it so if there aren't any related(similar) products to show other products. Here is the query:

select p.id,bg_product_name,unique_name,product_price,
promo_price, promo_end_date, available_qty,model,ptc.category_id, free_delivery, free_option
from products p, related_products rp, products_to_categories ptc where
 rp.product_id="10284" and rp.related_id=p.id and p.id=ptc.product_id and
 p.available_qty > 0 AND p.active="1" group by p.id limit 5

Thank you for any help and suggestions !

Use left join and put " rp.product_id="10284"" condition as join condition not in where.

like products p left Join related_products rp ON rp.related_id=p.id AND rp.product_id="10284"

follow with full query.

Try this

SELECT 
    p.id,bg_product_name,unique_name,product_price, promo_price, promo_end_date, 
    available_qty,model,ptc.category_id, free_delivery, free_option
FROM 
    products p
    LEFT OUTER JOIN products_to_categories ptc ON p.id=ptc.product_id
    LEFT OUTER JOIN related_products rp ON rp.related_id=p.id AND rp.product_id="10284"

WHERE
    p.available_qty > 0 AND p.active="1" 
GROUP BY p.id LIMIT 5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM