SELECT p.name,vld.qty_available current_stock,COUNT(DISTINCT pr.rack) rack_count FROM products p LEFT JOIN variation_location_details vld ON p.id=vld.product_id LEFT JOIN product_racks pr ON p.id=pr.product_id WHERE p.enable_stock=1 GROUP BY p.id,p.name,vld.qty_available ORDER BY rack_count DESC;