【问题标题】:join 2 fields in mysql to search both at the same time在mysql中加入2个字段以同时搜索
【发布时间】:2012-02-10 03:26:55
【问题描述】:

我正在尝试在字段名和姓氏中搜索关键字

$q1 = strtolower($_GET["q"]);
$q=str_replace(" ","%",$q1);
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter 
firstname LIKE '%$q%' OR lastname LIKE '%$q%' ORDER BY lastname";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) { echo $results }

这是我目前所拥有的,问题是如果你以 John Doe 为例,一旦你输入 John,它会找到它,它会找到它,但是 john doe ... 没有结果

【问题讨论】:

标签: php mysql sql


【解决方案1】:

我建议您绑定变量。否则,您将面临 sql 注入。

$stmt = $mysqli->prepare("select * from users where firstname like ? AND lastname like ?");
$stmt->bind_param('ss', $firstname,$lastname);

【讨论】:

  • 这是一个有用的建议,但与问题无关。
【解决方案2】:

类似

SELECT * FROM users where CONCAT(firstname, ' ', lastname) like '%$q%'

或者

SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'

如果需要倒车,试试这个:

SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%'
                       or CONCAT_WS(' ', lastname, firstname) like '%$q%'

(也就是说,如果搜索“A B”应该返回“A B”以及“B A”)

【讨论】:

  • 当查询“Doe John”时,它应该不返回“John Doe”。如果它应该,那么你有一个不同的问题。我错过了那部分。请确认您想要这样,我会尝试的。
【解决方案3】:

您必须拆分查询字符串并搜索每个字词

$query_terms = explode(" ", $q1);
$conditions = ''
foreach($query_terms as $term){
    $conditions = $conditions.' firstname LIKE "%'.$term.'%" OR lastname LIKE "%'.$term.'%"';
}

$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter $conditions ORDER BY lastname";

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多