所以搜索就像'Ozzie Smith'
第一个表有 (username, fname, lname) = osmith, ozzie, smith
第二个表有 (username, team) = osmith, cardinals
我需要连接第一个表中的名字和姓氏列,通过第二个表上的用户名加入它并返回团队名称。
我一直在尝试和尝试......大脑融化了。我需要你的帮助!
谢谢!
所以搜索就像'Ozzie Smith'
第一个表有 (username, fname, lname) = osmith, ozzie, smith
第二个表有 (username, team) = osmith, cardinals
我需要连接第一个表中的名字和姓氏列,通过第二个表上的用户名加入它并返回团队名称。
我一直在尝试和尝试......大脑融化了。我需要你的帮助!
谢谢!
由于它是 MySQL,因此您需要使用CONCAT
,而不是+
符号。我还添加了一个LOWER()
函数来避免大写字母不匹配问题:
select team
from table1
join table2 on table2.username = table1.username
where lower(concat(fname,' ',lname)) like lower('%Ozzie Smith%')
You're probably doing something like
WHERE fname LIKE '%Ozzie Smith%'
which will not work. fname
will contain only Ozzie
, and will never match against Ozzie Smith
. It would also not match if the user enters Smith, Ozzie
, or any other dual-name variant. You'll have to preprocess the search terms and do something like
WHERE (fname LIKE '%Ozzie%') or (fname LIKE '%Smith%')
OR (lname LIKE '%ozzie%') or (lname LIKE %Smith%')
This will get VERY painful as the number of search terms and fields being search goes up. You'd be better off using a FULLTEXT index, where it'll be a simple matter of
WHERE MATCH(fname, lname) AGAINST ('Ozzie Smith')
Why doesn't this work?
select
lname + ', ' + fname as playerName
, team as teamName
from table1
join table2 on table2.username = table1.username
Update:
where (fname + ' ' + lname) like '%Ozzie Smith%'