代码之家  ›  专栏  ›  技术社区  ›  The Pixel Developer

从相邻列表中选择并从下至上排序

  •  0
  • The Pixel Developer  · 技术社区  · 14 年前

    给定下表结构:

    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 ;
    

    是否有可能以这样的方式查询它:首先返回子项(自下而上)。

    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
    

    我们的目标是把它们装进Zendúu Acl的 addRole 方法,该方法要求在添加子级之前添加角色。

    我目前的方法是次优的(可能是错误的),需要两个查询。一个获取所有叶节点(其中父节点为空),另一个获取父节点按父节点排序的节点(DESC)。

    任何帮助都是非常感激的。

    2 回复  |  直到 14 年前
        1
  •  2
  •   AndreKR    14 年前

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

        2
  •  0
  •   Community Mike Causer    7 年前

    下面是我之前给出的一个基于角色的安全答案,可能会有所帮助: Writing an inheritance query written in SQL using an inner join?

    完整脚本如下: http://pastie.org/1213230