Question

Given the following table structure:

CREATE TABLE IF NOT EXISTS `roles` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `description` varchar(255) NOT NULL,
  `parent` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_name` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;

would it be possible to query it in such a way where the children are returned first (from bottom up).

1,  user,       Login privileges, granted after account confirmation, 17
2,  admin,      Administrative user, has access to everything.,       NULL
15, unverified, Users who have not validated their email address,     NULL
16, verified,   Users who have validated their email address,         NULL
17, guest,      A guest role, an anonymous visitor with no account,   NULL
18, moderator,  Role for doing staff duties,                          1

The goal is to load these into Zend_Acl's addRole method which requires roles to have been added before you add a child.

My current method is sub-optimal (and probably wrong) which requires 2 queries. One to get all the leaf nodes (where the parent is NULL) and another to get ones with parents ordered by the parent (DESC).

Any help is always much appreciated.

Was it helpful?

Solution

ORDER BY (parent IS NOT NULL) ASC, parent DESC

OTHER TIPS

Here's an role based security answer I gave a while back which might help: Writing an inheritance query written in SQL using an inner join?

Full script here : http://pastie.org/1213230

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top