简体   繁体   English

在 MySQL 数据库中搜索全名或名字或姓氏,名字和姓氏在单独的列中

[英]Searching full name or first or last name in MySQL database with first and last name in separate columns

I'm working with an existing database that has first name and last name seperated in the database.我正在使用一个现有的数据库,该数据库的名字和姓氏在数据库中是分开的。 I need to create a function that will take one search input and return results.我需要创建一个 function,它将接受一个搜索输入并返回结果。 say my database has a structure like....说我的数据库有这样的结构......

nameFirst nameLast
Joe       Smith
Joe       Jones
Joe       Brown

How could I, using MySql, take a search input that is say 'Joe Smith' and just get his row?我如何使用 MySql 进行搜索输入“Joe Smith”并得到他的行? But if I put just 'Joe' in the search field, return them all?但是,如果我在搜索字段中只输入“Joe”,是否会全部返回? Will I need to explode the string with a space?我需要用空格分解字符串吗? thanks!谢谢!

SELECT * 
FROM table
WHERE CONCAT( nameFirst,  ' ', nameLast ) LIKE  '%Joe%'  

Be sure to sanitize any user submitted parameters such as "Joe"请务必清理任何用户提交的参数,例如“Joe”

SELECT * FROM table WHERE CONCAT(nameFirst, ' ', nameLast) LIKE 'Joe%';

I suggest to use this if you are sure that your search input start with "Joe" to filter more.如果您确定您的搜索输入以“Joe”开头以过滤更多内容,我建议您使用它。

In my humble opinion in a lot of cases we don't know if the search input is the name or the surname so I suggest to use this:以我的拙见,在很多情况下我们不知道搜索输入是名字还是姓氏,所以我建议使用这个:

SELECT * FROM table WHERE CONCAT(nameFirst,  ' ', nameLast) LIKE  'SEARCH_INPUT%' OR CONCAT(nameLast,  ' ', nameFirst) LIKE 'SEARCH_INPUT%';
$sql = "SELECT * from add_contact  WHERE ( CONCAT(first_name, ' ',last_name)  LIKE '%$search%' OR first_name LIKE '%$search%' OR last_name LIKE '%$search%' OR company LIKE '%$search%') AND (archives='$archives') ORDER BY UNIX_TIMESTAMP(sort_date) DESC";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM