我是MySQL Procedures的新手,我正在尝试为表编写搜索过程。
CREATE PROCEDURE `Search`(
IN in_locality VARCHAR(200),
IN in_type VARCHAR(200),
IN in_city VARCHAR(200)
)
BEGIN
SELECT * FROM property_details MRP INNER JOIN property_image MRPI
ON MRP.basic_id=MRPI.basic_id
WHERE ((in_locality = '') or (MRP.locality = in_locality))
AND ((in_property_type = '') or (MRP.property_type = in_property_type))
AND ((in_city = '') or (MRP.city = in_city))
GROUP BY MRP.id;
END
现在这个程序适用于:
CALL Search('','','','mumbai');
但不适用于:
CALL Search('','',''mumbai','pune'');
在普通的SQL中,我可以使用此查询:
SELECT * FROM property_details where city in('mumbai','chennai')
但我不知道如何在程序中这样做。
答案 0 :(得分:2)
你的CALL示例有4个参数,而你的CREATE PROCEDURE语句只有3个。这是因为你试图指定多个城市。为此,您可以使用FIND_IN_SET函数将输入参数指定为逗号分隔列表(MySQL Docs for FIND_IN_SET)
相反尝试这个
CREATE PROCEDURE `Search`(
IN in_locality VARCHAR(255),
IN in_type VARCHAR(255),
IN in_city VARCHAR(255)
)
BEGIN
SELECT
*
FROM property_details MRP INNER JOIN property_image MRPI
ON MRP.basic_id=MRPI.basic_id
WHERE ( in_locality = '' XOR FIND_IN_SET( MRP.locality , in_locality ) )
AND ( in_property_type = '' XOR FIND_IN_SET( MRP.property_type , in_property_type ) )
AND ( in_city = '' XOR FIND_IN_SET( MRP.city , in_city ) )
GROUP BY MRP.id;
END
然后,您可以使用带有逗号分隔列表的字符串来调用它,例如以下示例。我还将它们更改为XOR,因为您不希望它搜索空字符串,并将所有3个搜索更改为FIND_IN_SET搜索。
CALL Search('','','','mumbai');
CALL Search('','','mumbai,pune');