简体   繁体   English

MySQL:从全名字段中提取名字或姓氏

[英]MySQL: Extracting First Name or Last Name From Full Name Field

In MySQL, I have a users table with a field called name.在 MySQL 中,我有一个 users 表,其中包含一个名为 name 的字段。 This name field can contain a full name or just first or last name.此名称字段可以包含全名或仅包含名字或姓氏。 See example below.请参见下面的示例。 I am having a hard time writing a query where if I type in the first name it should return me a list of everyone with that first name or full name.我很难编写一个查询,如果我输入名字,它应该返回一个包含该名字或全名的每个人的列表。

//MySQL query for finding user by name
findUserByName: (name) =>{
  return new Promise((resolve, reject) =>{
  pool.query(
    `SELECT id, user_image, name, email, is_online FROM users WHERE name = ?`,
    [name],
  (error, results, fields) =>{
    if(error){
      return reject(error);
    }
    else{
        return resolve(results);
    }
  }
);
})
},
//If I type mike it should return me all three of the below names. If I type mike jones it should only return me mike jones.
+------------+
|    name    |
+------------+
| Mike Jones |
+------------+
| Mike Brady |
+------------+
| Mike       |
+------------+

Doesn't like do what you want?like做你想做的事?

SELECT id, user_image, name, email, is_online 
FROM users 
WHERE name LIKE CONCAT('%', ?, '%')

This searches for the parameter string anywhere in name .这将在name中的任何位置搜索参数字符串。 If you wanted to search at the beginning of the string only, you would change the predicate to:如果只想在字符串的开头搜索,可以将谓词更改为:

WHERE name LIKE CONCAT(?, '%')

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

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