I have one table which contain meta records. I need best search results from records.
Suppos If I search in table with following keywords :
Beautiful well-maintained Remodeled
Then my result should be this type:
Firstly all records contains all three keywords, Second records contain any two records and last records contain any one keywords.
I have tried fulltext search and Like query but I didn't get results.
Count the matches per record ond order by this:
select *
from
(
select
mytable.*,
case when lower(col) like '%beautiful%' then 1 else 0 end +
case when lower(col) like '%well-maintained%' then 1 else 0 end +
case when lower(col) like '%remodeled%' then 1 else 0 end as matches
from mytable
)
where matches > 0
order by matches desc;
I would use PHP explode to get each word separated and adjust my SQL query accordingly using AND and OR statements using Likes:
$keywords = explode(" ", $_REQUEST['q']);
$sql_query = $dbh->prepare("QUERY");
$i = 0;
foreach($keywords as $keyword) {
$sql_query->bindParam($i, $keyword);
}
I know this code alone wont work, but it should point you in the right direction.
Using LIKE
Has 3:
SELECT * FROM <table>
WHERE <column> LIKE '%Beautiful%'
AND <column> LIKE '%well-maintained%'
AND <column> LIKE '%Remodeled%'
Any Two:
SELECT * FROM <table>
WHERE ( <column> LIKE '%Beautiful%' AND <column> LIKE '%well-maintained%' )
OR ( <column> LIKE '%Remodeled%' AND <column> LIKE '%well-maintained%' )
OR ( <column> LIKE '%Beautiful%' AND <column> LIKE '%Remodeled%' )
Any One:
SELECT * FROM <table>
WHERE <column> LIKE '%Beautiful%'
OR <column> LIKE '%Remodeled%'
OR <column> LIKE '%Beautiful%'
Using Regex for any match:
SELECT * FROM <table> WHERE <column> REGEXP '(.*)Remodeled(.*)|(.*)well-maintained(.*)|(.*)Beautiful(.*)'