2012-03-22 90 views
0

好吧,我正在从网页检索fullname来过滤客户列表,我不确定哪部分是名字或姓氏,所以我需要运行类似下面的查询:在SQL中使用LIKE运算符时合并字段

"SELECT sc.*, c.firstname, c.lastname,c.email FROM scoop_customer AS sc LEFT JOIN 
customer AS c ON sc.customer_id = c.customer_id WHERE c.firstname + ' ' + c.lastname 
LIKE '%".$fullname."%'" 

但它似乎没有工作给我,即使我试了很多次,通常它应该已经从数据库中返回值。你能告诉我我做错了吗?

+2

** WARNING **你的代码也许容易受到SQL注入攻击。 – 2012-03-22 15:20:55

+1

或者如果您搜索“%”且表格足够大,则拒绝服务 – 2012-03-22 15:29:51

回答

1

使用CONCAT(c.firstname , ' ' , c.lastname)

2

尝试CONCAT

WHERE concat(c.firstname, ' ', c.lastname) LIKE '%".$fullname."%'" 
1

CONCAT会为这些操作

请参见mysql的文档

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat

“选择SC。是很好* c.firstname,c .lastname,c.email FROM scoop_customer AS sc LEFT JOIN customer AS c ON sc.customer_id = c.customer_id WHERE CONCAT(c.firstname,'',c.lastname)LIKE'%“。mysql_real_escape_string($ fullname)。” %'“

1

我会把全名分成第一个和最后一个,做两个类似的检查,并在每个开始时删除通配符%。连接和通配符开始时会破坏名称字段上的任何索引。

当然,如果您在表格中只有几千名客户,索引不会太多,但是当您进入100,000时,您会感觉到它!

1

假设你还没有逃过它,以前我已经添加了mysql_real_escape_string。
对于这个问题,关键是OR,但不CONCAT

".... WHERE c.firstname LIKE '%".mysql_real_escape_string($fullname)."%' 
     OR c.lastname LIKE '%".mysql_real_escape_string($fullname)."%'"