使用MySQL存储过程进行多列搜索

时间:2011-01-21 22:17:52

标签: mysql stored-procedures

我是MySQL存储过程的新手,需要制作一个MySQL存储过程来搜索具有多个列过滤器的产品列表。如果我没有发送带有值的所有参数,下面发布的代码将不会返回任何值。如果所有参数都为空,它应显示所有产品,并在发送其他参数时过滤结果。

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 IS 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 ;

有人能指出使用多列过滤器进行存储过程搜索的正确方法吗?

1 个答案:

答案 0 :(得分:1)

这个怎么样:

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, '%'))