如何在mysql存储过程中使用一个条件

时间:2016-03-12 12:39:52

标签: php mysql sql select stored-procedures

我想写一个MySQL存储过程并给出4个变量_keyword,_catid,_low和high如果_catid不是空的过滤结果,其中category_id列等于_catid,如果它(_catid)为空,则不执行以下任何操作:< / p>

CREATE DEFINER = `root`@`localhost` PROCEDURE `sp_company_search` (
    IN `_catid` INT,
    IN `_keyword` VARCHAR (200) CHARSET utf8,
    IN `_low` INT,
    IN `_high` INT
) NO SQL SELECT
    i.images_id,
    c. NAME,
    c.address,
    c.id,
    cat.title,
    c.extra
FROM
    company c
LEFT JOIN category cat ON c.category_id = cat.id
LEFT JOIN company_images i ON c.id = i.company_id
WHERE
    (
        c. NAME LIKE _keyword
        OR c.extra LIKE _keyword
    ) 

    -- what i need TO DO: 
    -- IF (_catid != '') THEN { put "and c.category_id=_catid" IN QUERY }

    ORDER BY
        c.id DESC
    LIMIT _low, _high

1 个答案:

答案 0 :(得分:1)

您可以使用or逻辑运算符来模拟此行为:

SELECT
    i.images_id,
    c. NAME,
    c.address,
    c.id,
    cat.title,
    c.extra
FROM
    company c
LEFT JOIN category cat ON c.category_id = cat.id
LEFT JOIN company_images i ON c.id = i.company_id
WHERE
    (
        c. NAME LIKE _keyword
        OR c.extra LIKE _keyword
    ) AND
    (_catid = '' OR c.category_id=_catid)
    ORDER BY
        c.id DESC
    LIMIT _low, _high