What is the best way to sort a result set in MySQL based on a field value that could come from multiple tables?
For the sake of simplicity, assume there are four tables in the DB. The primary table contains a number of fields, but particularly it contains a column with the name of another table and a foreign key to a record in said table. Each of the three foreign tables contain a name column that I would like to sort the results by in the primary table.
Example primary table:
+----+---------------+------------+-------------+
| id | foreign_table | foreign_id | more_fields |
+----+---------------+------------+-------------+
| 1 | students | 9182 | blah, blah |
| 2 | students | 1008 | blah, blah |
| 3 | parents | 3827 | blah, blah |
| 4 | teachers | 4523 | blah, blah |
| 5 | teachers | 1092 | blah, blah |
+----+---------------+------------+-------------+
Example foreign (students) table:
+-------+--------------+-------------+
| id | name | more_fields |
+-------+--------------+-------------+
| 9182 | Joe | blah, blah |
| 1008 | Sally | blah, blah |
+-------+--------------+-------------+
Is this possible in MySQL? Or do I need to loop through the results in PHP and create an array to sort by and then use something like array_multisort()? If using an array, would it be efficient to loop through thousands of rows just to sort the results?
Any help is greatly appreciated.
Using three
LEFT JOINs (students, parents, teachers) and listing each in theORDER BYought to do the job if youCOALESCE()the names from the other three tables together:In the long run, I would suggest changing this schema to store all of the different types of names in one table, with an identifier in that table indicating whether it is a student, teacher, or parent.