Search mysqli for multiple values in one column, return matching another, sort by count of occurrences?

时光怂恿深爱的人放手 提交于 2020-01-14 02:59:10

问题


Before I start, here is the sample format of the database:

id  date         title            content
--------------------------------------------------------------
1   YYYY-MM-DD   some text here   lots of stuff to search here
2   YYYY-MM-DD   some text here   lots of stuff to search here
3   YYYY-MM-DD   some text here   lots of stuff to search here

I currently have something set up to get the id of a row, then assign the date, title, and content to PHP variables to display in different places on a page (it's a blog, these are posts).

Now I'm trying to make a function that will search the content for each string in an array (the code already splits words entered into the search box by spaces into an array, so entering cat hotdog suit will give [0]cat [1]hotdog [2]suit).

I have a loop set up that performs a query on each of the strings:

foreach ($queryArray as $queryArrayString) {
    // query the content column for $queryArrayString
}

However, I can't figure out what query I should use to find the id of the post that the string occurs in. I'd like to assign it to a variable ($results). After reversing the array, so higher ids (newer results) show up first, I'd like to find the titles of each id and store it like this:

id (let's say it is 3) => matching title
id (let's say it is 1) => matching title

Is this possible? I've tried several different queries, and none worked, but one took 2 minutes and loads of memory to attempt.

Any help would be appreciated.

EDIT: I've created a text index of the title and content columns (I'd like to search both), shown in this image.

Is it possible to search this? Like I've said in the comments, I'd just need it to return the corresponding id and title somehow. (Title for result link text, id for link destination: <a href="blog?p=[id]">[title]</a> is the format I'm using


回答1:


In ideal world, there are complex solutions available like Apache SOLR or Elasticsearch for indexing records and return efficiently when multiple text-search-terms are provided. Luckily, you can achieve such results by trying something like this (not tested)..

$searchTerms = "cat hotdog suit";
$searchArray = explode(' ',$searchTerms);

$conditions = array();
$foreach (searchArray as $searchTerm){
    $conditions[] = 'title-content LIKE %'.searchTerm.'%';
}

$query = '
SELECT
    tableName.id,
    CONCAT_WS(' ', tableName.title,tableName.content) as title-content
FROM
    tableName
WHERE
    '.implode(' OR ', $conditions);


来源:https://stackoverflow.com/questions/24480864/search-mysqli-for-multiple-values-in-one-column-return-matching-another-sort-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!