douchilian1009
douchilian1009
2018-05-18 16:27

使用PHP或SQL按发生优先级排序MYSQL结果

已采纳

I use the php script below to query mysql and to display:

$sql1 = $con->prepare("SELECT item FROM product WHERE item LIKE ?");
$q = '%' . $q . '%';
$sql1->bind_param("s", $q);
$sql1->execute();
$sql1->bind_result($item);

while ($sql1->fetch()) {          
echo "<div>$item</div>

Let say search $q = 'test tube' The result did come out like this:

brush for test tube
test tube glass
test tube plastic

(This is logic since the items are indexed alphabetically in mysql)

But I after I get result array from query, I want to use PHP to sort it again by giving priority first to which ever item that meets the search keyword at the front most.

I expect the result like this:

test tube glass
test tube plastic
brush for test tube

How can I do that? Any suggestion?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqu2712 douqu2712 3年前

    You could just ORDER BY INSTR(item, ?).

    点赞 评论 复制链接分享