简体   繁体   中英

how to use a condition in mysql stored procedure

I want to write a MySQL stored procedure and give 4 variables _keyword , _catid,_low and high then if _catid was not empty filter results where category_id column equals _catid and if it(_catid) was empty do nothing something like this:

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

You can emulate this behavior with the or logical operator:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM