简体   繁体   中英

FULLTEXT Search Multiple Columns in MySQL?

So I've been struggling with this for the last couple days.. I have music genres. Separated by primary and secondary columns. Rock / Progressive rock, etc. And i have it so it'll search one column, just fine. But i'd like it to search either column. searching for help on google. I found that a FULLTEXT search in theory should do this. I setup the FULLTEXT index on both the Primary and secondary columns.. But I haven't been able to get it working.

this is my code that works for the single column:

    $query = sprintf("SELECT * FROM musicgenres WHERE secondary LIKE '%%%s%%' LIMIT 20", mysql_real_escape_string($_GET["q"]));

$arr = array();
$rs = mysql_query($query);

while($obj = mysql_fetch_object($rs)) {
    $arr[] = $obj;
}

$json_response = json_encode($arr);

if($_GET["callback"]) {
    $json_response = $_GET["callback"] . "(" . $json_response . ")";
}


$final = str_replace(genre_id, id, $json_response);
echo $final;

(It returns the results in a JSON format)

I've tried to follow this tutorial i've found that gives this as an example:

 $term = "Search Term";

    $sql = "SELECT *, MATCH(title, content) AGAINST('". $term ."') as score FROM pages WHERE MATCH (title, content) AGAINST('". $term ."') ORDER BY score DESC";
    $query = mysql_query($sql);

the question seems to be either in the SELECT query. or when i do combine it. it causes an error with this line:

while($obj = mysql_fetch_object($rs)) {

the most recent Select query i tried was:

$term = mysql_real_escape_string($_GET["q"]);

$sql = "SELECT *, MATCH(primary, secondary) AGAINST('". $term ."') as score FROM musicgenres WHERE MATCH (primary, secondary) AGAINST('". $term ."') ORDER BY score DESC";

I've also tried with: LIKE '%%%s%%' (which would be more useful. as partial matches would be nice)

I'm not 100% sure what you are looking for but if you want to search multiple columns something like this should work:

"SELECT * FROM musicgenres WHERE secondary LIKE '%%%s%%' OR primary LIKE '%%%s%%' LIMIT 20"

Hope that's close to what you are looking for.

Maybe you want to add indexes that enclose the columns you want to search:

ALTER TABLE `table` 
ADD FULLTEXT `fulltext_idxAll` (`column1`, `column2`,`column3`);
SELECT * FROM `table` 
WHERE MATCH (`column1`, `column2`,`column3`) 
AGAINST ('whateveryouwanttosearch')

hope this is useful for you.

Ok try this query

SELECT column1, column2, ..., MATCH(primary, secondary) AGAINST('". $term ."') as score 
FROM musicgenres 
WHERE MATCH (primary, secondary) AGAINST('". $term ."') 
ORDER BY score DESC"

If it dosent work try to remove match() against() from select clause

SELECT column1, column2, ... FROM .... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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