0

I have the following MySQL query:

SELECT * FROM users WHERE name LIKE '%jack%'

I want it to order by how much it's like jack so

  1. jack
  2. jacker
  3. majack

I can also use PHP.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
e---
  • 40
  • 8

4 Answers4

3

I think you can accomplish what you want by using full text search function in mysql. Your query will be like this:

SELECT name, MATCH (name) AGAINST ('jack') as score 
FROM users ORDER BY score DESC;

There are some conditions you need to take into consideration when using full search text:

  • The mysql engine should support this functions. I think InnoDB 5.6 and MYISAM 5.5 support that.
  • You have to add a FULLTEXT index in your table definition.

You can see a working demo here: http://sqlfiddle.com/#!9/72bf5/1

More info about full search text in MySQL here: http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html

Also, here is a working example I wrote on PHP using similar_text and sorting array functions: http://ideone.com/UQpBFk

Hope it helps!

emco
  • 4,589
  • 3
  • 18
  • 20
0

I don't think you can do this kind of thing with plain SQL. The first thing you need to do is define what it means for two strings to be similar, for which there are various metrics. You should probably pick one of those and write a stored procedure to sift through the data.

Gigi
  • 28,163
  • 29
  • 106
  • 188
  • You can use whatever you like. A stored procedure gives you the advantage of doing such operations closer to the database, so that data you don't need doesn't even need to take up memory used by the PHP runtime. – Gigi Apr 12 '14 at 12:23
0

As every one mentioned, you can't achieve this using normal way other than using full text search but if you know all the different pattern before hand then you can use FIELD function to achieve something which resemble a approx result like

SELECT * FROM users WHERE name LIKE '%jack%'
ORDER BY FIELD (name,'jack','jacker','majack') 
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • OP's expected result may be a sorted order list than a limited amount of rows. Your result works for limited with specific/known values. – Ravinder Reddy Apr 12 '14 at 12:52
  • @Ravinder, yes and that's why it's clearly mentioned in answer that `approx result`. It's not an exact solution. – Rahul Apr 12 '14 at 12:54
0

Try something like this:

$query = mysql_query("SELECT * FROM users WHERE name LIKE '%jack%' ORDER BY name ASC ");

while($fetchdata=mysql_fetch_array($query))
{
echo $fetchdata["name"] ; 
}
Neeraj Kumar
  • 506
  • 1
  • 8
  • 19