Get row position after sorting mysqli result

I am looking for a way to get the location of a specific item after sorting my mysqliresult. I have a table like this:

id_______|_Name_____________|_ParentID
58       | Carl             | 15
55       | Clark            | 15
12       | David            | 4
23       | Sophie           | 15
45       | Amanda           | 15

I'm only interested in lines with ParentID 15, and I want to sort them by their name. Then I want to look at a specific element, say id 55 (Clark) and find out what line number it fits. I want to create a table as follows:

id_______|_Name_____________|_ParentID
45       | Amanda           | 15
58       | Carl             | 15
55       | Clark            | 15
23       | Sophie           | 15

Then I want to get number 3 when I am interested in Clark, since his row is the third row in this new table.

mysqli? , , , , , thorugh .

!

+4
4

:

SELECT t.*,
       (SELECT COUNT(*) FROM YourTable s
        WHERE t.parent_id = s.parent_id 
           and t.name <= s.name) as Cnt
FROM YourTable t

:

id_______|_Name_____________|_ParentID__|_Cnt
58       | Carl             | 15        |  2
55       | Clark            | 15        |  3
12       | David            | 4         |  1
23       | Sophie           | 15        |  4
45       | Amanda           | 15        |  1

Cnt , , :

SELECT tt.cnt 
FROM (...above query here...) tt
WHERE tt.name = ? --optional
  AND tt.parent_id = ? --optional
+2

Clark, :

select count(*)
from t
where t.ParentId = 15 and
      t.Name <= 'Clark';

t(Name, ParentId) .

0

SELECT T.*,  if(@a, @a:=@a+1, @a:=1) as rownum 
FROM T
WHERE ParentID=15
ORDER BY Name

SQLFiddle

0

Try

SELECT * FROM table_name WHERE parent_id = 15 ORDER BY name ASC;
-1

All Articles