I have the following 'departments'
table:
+-------+-------------+-------------------+
| rowid | department | parent_department |
+-------+-------------+-------------------+
| 10 | Main Office | NULL |
+-------+-------------+-------------------+
| 11 | Back Office | 10 |
+-------+-------------+-------------------+
| 12 | Commercial | NULL |
+-------+-------------+-------------------+
| 13 | Outdoor | NULL |
+-------+-------------+-------------------+
| 14 | Beach | 13 |
+-------+-------------+-------------------+
| 15 | Gardening | 13 |
+-------+-------------+-------------------+
| 16 | Accounting | 10 |
+-------+-------------+-------------------+
and I would like to order it based on rowid and parent_department as such:
+-------+-------------+-------------------+
| rowid | department | parent_department |
+-------+-------------+-------------------+
| 10 | Main Office | NULL |
+-------+-------------+-------------------+
| 11 | Back Office | 10 |
+-------+-------------+-------------------+
| 16 | Accounting | 10 |
+-------+-------------+-------------------+
| 13 | Outdoor | NULL |
+-------+-------------+-------------------+
| 14 | Beach | 13 |
+-------+-------------+-------------------+
| 15 | Gardening | 13 |
+-------+-------------+-------------------+
| 12 | Commercial | NULL |
+-------+-------------+-------------------+
So that for each rowid , find if 'parents_departments'
exists and show order it as the following.
Please note that I have not designed the current table and sadly I do not have the permission to change it
Try this:
SELECT rowid, department, parent_department
FROM departments
ORDER BY IFNULL(parent_department, rowid), rowid;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.