php - MySql - Sort persons by name and partner -


i'm dealing following problem in mysql/php web application:

a table of persons looking having columns:

id, firstname, surname, idofpartner, street, zipcode

should ordered surname of person should followed partner of person result like

person a
partner of person (no matter surname starts with)
person b
partner of person b
...

i'm doing simple order surname , putting them in php code.

at moment query

select * customers order surname, firstname 

the rest done in php code slow.

can achieved in database? , better performance wise?

ok, let's build up.

the list of persons, without partners, is:

select a.surname, a.firstname,        a.surname sortsurname, a.firstname sortfirstname, a.id sortid,        0 role   person 

now fetch partners of persons. in join b partner.

select b.surname, b.firstname,        a.surname sortsurname, a.firstname sortfirstname, a.id sortid,        1 role   person   join person b on b.id = a.idofpartner 

now combine these 2 tables union , sort whole mess on sorting names , role

select surname, firstname, role ( select a.surname, a.firstname,        a.surname sortsurname, a.firstname sortfirstname, a.id sortid,        0 role   person               union select b.surname, b.firstname,        a.surname sortsurname, a.firstname sortfirstname, a.id sortid,        1 role   person   join person b on b.id = a.idofpartner  ) both order sortsurname, sortfirstname, sortid, role 

the trick here assign role of 0 person , role of 1 partner, , create columns in result set allow sorting. added sortid parameter deal case more 1 person shares name.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -