Reputation: 63
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
Upvotes: 1
Views: 43
Reputation: 311853
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
Upvotes: 1