1

EDIT : my question is not clear, so I've reformulated it here : Order sql result by occurrence of a set of keywords in a string

I'm improving my search system for my website. I'm trying to use and increment variables in sql request, like that...

SET @titlematch = 0;
SELECT *,
CASE 
    when title like '%apple%' then (SET @titlematch = @titlematch+1)
    when title like '%orange%' then (SET @titlematch = @titlematch+1)
    when title like '%other_keyword_searched%' then (SET @titlematch = @titlematch+1)
    (...)
END,
(...)
FROM pages  
(...)
ORDER by @titlematch desc

In fact, titlematch should be incremented each time that a keyword is in the title. If there's "apple" and "orange" in the title, titlematch should be equal to 2. But actually, it doesn't work...

(sorry for my english)

Community
  • 1
  • 1
Maxime R.
  • 133
  • 1
  • 9

2 Answers2

0

I think it fails because it must handle all the data,if title like someWordYouDontAcccountFor it will fail.You must account for all possible cases or use else.

Mihai
  • 26,325
  • 7
  • 66
  • 81
0

In response to your comment (Yes, always), I rewrite your query in this way:

SELECT *, (select count(*) from pages p2 where p1.field_date < p2.field_date) as pos
(...)
FROM pages p1
(...)
ORDER by (select count(*) from pages p2 where p1.field_date < p2.field_date) desc

In this way you count every rows before the actual (I've based my count on ipotetic field_date but if you want you can change your condition), so you have an incremental value for each row, and finally, I add this condition in order by clause.

Tell me if it's OK

Joe Taras
  • 15,166
  • 7
  • 42
  • 55