简体   繁体   English

mysql 类似查询,如何针对表中的两列进行排序但按一列匹配的结果排序

[英]mysql like query, how can you sort targeting two columns in a table but sorting by the results matched by one column

Using the code below, i am able to return all products that match the search word.使用下面的代码,我能够返回与搜索词匹配的所有产品。 However they order in a way that a product with a name different from the search phrase appears first and one with a matching name later because the description had a match.但是,它们的排序方式是,名称与搜索词组不同的产品首先出现,而名称匹配的产品随后出现,因为描述匹配。

How can i sort and return the products whose name matches the search phrase first?如何排序并返回名称首先与搜索词组匹配的产品?

    $sqli = "
SELECT * 
  FROM product 
 WHERE";

Foreach($strarray as $key=>$value){
If($key > 0){
$sqli = $sqli . "OR";
}
$sqli = $sqli . " (Name LIKE '%" . $value . "%' or Description LIKE '%" . $value . "%')";
}

Add an ORDER BY clause:添加ORDER BY子句:

$ssql .= " ORDER BY Name LIKE '%" . $value . "%' DESC"

A boolean expression is 1 for TRUE and 0 for FALSE, so sorting by a condition orders by whether the row matches the condition. boolean 表达式为 1 表示 TRUE,0 表示 FALSE,因此按条件排序按行是否与条件匹配。

BTW, you should learn to use prepared statements to prevent SQL injection.顺便说一句,您应该学会使用准备好的语句来防止 SQL 注入。 See How can I prevent SQL injection in PHP?请参阅如何防止 PHP 中的 SQL 注入?

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

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