I would like to create query like this:
$get_products = "SELECT P.*, C.`category_name`, GROUP_CONCAT(`category_name` SEPARATOR ', ') AS `cat`
FROM `products` P
NATURAL JOIN
`categories` C
NATURAL JOIN
`product_to_categories`";
WHERE
FIND_IN_SET(`category_name`, :selected_categories)
AND `product_price` BETWEEN :price_min AND :price_max
GROUP BY `product_name`
ORDER BY 1 DESC ";
$db = getConnection();
$stmt = $db->prepare($get_products);
$stmt -> bindValue(selected_categories, $selected_categories);
$stmt -> bindValue(price_min, $price_min);
$stmt -> bindValue(price_max, $price_max);
the problem is that string $selected_categories in some cases is empty, and when it is empty obviously nothing is found.
Is there any parameter which I can use (for example $selected_categories = '*';
) and it will cause that FIND_IN_SET will find everything? or should I create completely new query for case when $selected_categories is empty?
You can solve this with simple logic
WHERE
(
:selected_categories = '*' OR
FIND_IN_SET(`category_name`, :selected_categories)
)
AND `product_price` BETWEEN :price_min AND :price_max
You can use a variable to reference the same replacement parameter twice:
WHERE IF((@selected_categories:=:selected_categories)='*',1,FIND_IN_SET(category_name,@selected_categories))
and test some value you want to mean all ('*' in this example, you could use ='' or IS NULL or something else).
Some prefer using the SQL standard CASE instead of IF; that would look like:
WHERE
CASE
WHEN (@selected_categories := :selected_categories) = '*' THEN 1
ELSE FIND_IN_SET(category_name, @selected_categories)
END
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.