[英]Why does mysql LIKE query sometimes fail to return results?
環境詳細信息(XAMPP)Apache / 2.4.4(Win32)OpenSSL / 1.0.1e PHP / 5.5.3服務器版本:5.6.11-MySQL Community Server
我有一個搜索欄,用於搜索與之沒有關系的新用戶。 當我添加搜索參數時,有時會得到結果,有時卻不會得到結果。
為什么會發生以下情況?
搜索:“ Sarah T”返回有關用戶Sarah Testname的信息
在搜索:“ Sarah測試”時,不返回任何內容。
我使用trim()和str_replace()刪除白色字符。 即“ Sar ah”成為“ Sarah”
在數據庫中:
firstname | lastname
Sarah | Testname
Robert | Richards
使用以下存儲過程:
DROP PROCEDURE IF EXISTS `get_contact_list_new`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_contact_list_new`(
IN _id bigint(20),
IN _args varchar(255)
)
BEGIN
IF _args IS NULL THEN
SELECT u.* FROM user_user_relationship AS uur
RIGHT JOIN user AS u
ON uur.user_id_one = _id AND u.user_id = uur.user_id_two
WHERE u.user_id != _id AND uur.status IS NULL;
ELSE
SET @args = CONCAT("%",_args,"%");
SELECT u.* FROM user_user_relationship AS uur
RIGHT JOIN user AS u
ON uur.user_id_one = _id AND u.user_id = uur.user_id_two
WHERE u.user_id != _id AND uur.status IS NULL AND
(u.firstname LIKE @args OR u.lastname LIKE @args OR (u.firstname + u.lastname) LIKE @args OR u.username LIKE @args OR u.email LIKE @args) ;
END IF;
END//
有時,我可以在中間添加隨機字符,即sarzqtes並返回Sarah Testname。
這是MySQL Like查詢的錯誤嗎? 還是我的查詢? 不管是什么-您能向我解釋原因嗎?
這些問題也發生在phpmyadmin mysql控制台上。
call get_contact_list_new(1,"saraht")
返回有關Sarah Testname的信息
call get_contact_list_new(1,"sarahtes")
什么也不返回。
(u.firstname + u.lastname) LIKE @args
應該:
CONCAT(u.firstname, " ", u.lastname) LIKE @args
+
是數字加法,不是字符串連接。 並且您需要在名字和姓氏之間放置一個空格,否則您將得到SarahTestName
,它將與%Sarah Testname%
不匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.