开发者

Multiple column search with MySQL Stored Procedure

I'm a newbie on MySQL Stored Procedures and need to make a MySQL stored procedure to search a list of products with multiple column filters. The code posted below won't return any values if I don't send all parameters with values. It should display all products if all parameters are empty and filter results when sending other parameters.

DELIMITER $$

USE `537174_alsuper`$$

DROP PROCEDURE IF EXISTS `ListarProductos`$$

CREATE DEFINER=`537174_alsuper`@`%` PROCEDURE `ListarProductos`(
            IN Token VARCHAR(50),
            IN cID INT(11), 
            IN pID INT(11),
            IN os INT(1),
            IN productName VARCHAR(255)
            )
BEGIN

    DECLARE BaseToken VARCHAR(50);
    SELECT TOKEN_VALUE INTO BaseToken FROM web_service_tokens WHERE 1 ORDER BY TOKEN_ID DESC LIMIT 1;

    IF (Token = BaseToken) THEN

    SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
    FROM SC_products a, SC_product_pictures d 
    WHERE a.ordering_available='1' AND d.productID=a.productID AND

    CASE
        WHEN cID I开发者_开发技巧S NOT NULL 
        THEN a.categoryID = cID
        WHEN cID IS NULL 
        THEN 1 = 1
    END

    AND

    CASE
        WHEN pID IS NOT NULL 
        THEN a.productID = pID
        WHEN pID IS NULL 
        THEN 1 = 1
    END

    AND

    CASE

        WHEN os IS NOT NULL 
        THEN a.on_special = os
        WHEN os IS NULL 
        THEN 1 = 1
    END

    AND

    CASE
        WHEN productName IS NOT NULL 
        THEN a.name_en LIKE CONCAT('%',productName,'%')
        WHEN productName IS NULL 
        THEN 1 = 1
    END


    ORDER BY a.name_en ASC;

    END IF;

    END$$

DELIMITER ;

Can anyone point to the right way on doing a stored procedure search with multiple column filters?


How about this:

SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
FROM SC_products a
INNER JOIN SC_product_pictures d ON d.productID = a.productID
WHERE a.ordering_available='1' AND
(cID IS NULL OR a.categoryID = cID) AND
(pID IS NULL OR a.productID = pID) AND
(os IS NULL OR a.on_special = os) AND
(productName IS NULL OR a.name_en LIKE CONCAT('%', productName, '%'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜