php – 在mysql中搜索关键字并获取至少包含5个关键字的数据

我有一个大型数据库,可以保存各种图像.

每个图像都有多个以逗号(,)分隔的关键字.

现在,当用户点击图像时,前端会显示一些图像,它会显示至少有5个常用关键字和所选关键字的图像.我很困惑怎么做.

最佳答案 首先将图像的所有关键字都添加到您想要搜索的内容中,就像您点击关键字为的图像一样:

$keywords = "good,beautiful,nice,weather";

现在添加循环以通过爆炸获取数组中的所有关键字.

$exploded = explode(",",$keywords);

现在在$爆炸上使用foreach循环来匹配db.

像这样使用你的查询

$matched = array();
foreach($exploded as $key => $searchValue) 
{   
    select * from cars where colors like '%,$searchValue,%';
    //you can use find in set instead like:
    select * from cars where find_in_set($searchValue,colors);

    //code here to check matched or not.
   //if result matched add 1 in count of same index in matched array like :
   $matchedimageid = //get image id from query and add that in array.
   $matched[$matchedimageid] = $matched[$matchedimageid]+1;
}

//code here to get all image ids from $matched array whose value greater than or equal to 5. and show them in list

注意:此逻辑适用于您当前的情况,但最佳解决方案是将关键字放在单独的表中.

点赞