I have a table, InnoDB, with columns id(int), name(varchar) and info(text). I need to search the name and info columns of the table using a given term and rank the matching records from high to low, according to the number of ‘hits’ in the two columns combined for each record.
I’ve trawled about but I’ve never ever done anything like this with MySQL before and find it all a little confusing… case and match etc. etc.
Can anyone offer some quick help?
This is as far as I’ve got:
SELECT count(*) as count
FROM artistmanager_artists WHERE
case when 'name' LIKE '%a%' then 1 else 0 end
+ case when 'info' LIKE '%a%' then 1 else 0 end
ORDER BY count ASC
(‘a’ being the search term)
Which returns one row and one column, ‘count’, with a value of three… which I’m guessing is because I’ve got three records in the table at the mo?
I’ve also found and tried this:
SELECT *
FROM `artistmanager_artists`
WHERE `name` LIKE '%a%'
AND (
`info` LIKE '%a%'
)
ORDER BY (
(
CASE WHEN `name` LIKE '%a%'
THEN 1
ELSE 0
END
) + (
CASE WHEN `info` LIKE '%a%'
THEN 1
ELSE 0
END
)
) DESC
This returned all but one record, in no obvious order, when I KNOW the record it didn’t return contains a lot of ‘a’!
I have done it! Thanks to @MvG for the inspiration. Since I’m much better with my PHP than I am my MySQL I solved the problem by doing the following: (I’m using Codeignite btw)
Which returns an array with the ids of the records as key and a rank value, sorted high to low. I tested it and it works so I’m chuffed.
Thanks to all for help with the lateral thinking!