Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort MySQL results alphabetically but with search term match first using CodeIgniter ActiveRecord?

Let say we have 4 items in a table:

  1. Michel Jordan
  2. Tom Mark Jordan
  3. Jordan John
  4. Adam Jordan Robert

The search term is "Jordan", how can i get the results sorted alphabetically but with search term match first like this:

  1. Jordan John
  2. Michel Jordan
  3. Tom Jordan Robert
  4. Adam Mark Jordan

Im using this code, but not getting what i want:

$this->db->select('id, name');
$this->db->from('users');
$this->db->like('name', $search_term);
$this->db->order_by('name', 'asc');
$query = $this->db->get();
like image 757
Waleed Asender Avatar asked Jan 09 '13 15:01

Waleed Asender


2 Answers

Try this:

SELECT id, fullName 
FROM test 
ORDER BY FIND_IN_SET('Jordan', REPLACE(fullName, ' ', ',')), fullName;

Check this link SQL FIDDLE DEMO

OUTPUT

| ID |          FULLNAME |
|----|-------------------|
|  1 |       Jordan John |
|  2 |     Michel Jordan |
|  4 | Tom Jordan Robert |
|  3 |  Adam Mark Jordan |
like image 142
Saharsh Shah Avatar answered Nov 05 '22 11:11

Saharsh Shah


You can try this:

$this->db
     ->select('id, fullName')
     ->from('test')
     ->order_by("FIND_IN_SET('Jordan', REPLACE(fullName, ' ', ',')) , fullName");
$query = $this->db->get();
like image 38
Code Prank Avatar answered Nov 05 '22 11:11

Code Prank