1

Here is an example of what I want. I have an id and I want to select * the id and all it's parent. Is it possible?

cn.Execute("create table if not exists Link( id INTEGER PRIMARY KEY AUTOINCREMENT , `parent`  INT , `val`  INT  NOT NULL , FOREIGN KEY (parent) REFERENCES Link(id));", new { });
cn.Execute("insert into Link(val) values(3)");
cn.Execute("insert into Link(parent, val) values(last_insert_rowid(), 5)");
cn.Execute("insert into Link(parent, val) values(last_insert_rowid(), 9)");
var id = cn.Query<long>("select last_insert_rowid()", new{});
cn.Execute("insert into Link(parent, val) values(last_insert_rowid(), 8)");
cn.Execute("insert into Link(val) values(4)");
4

1 回答 1

0

递归 sql 函数可能会有所帮助。我遇到了这个非常具体的需求,谢天谢地,因为我使用的是 SQLAlchemy(ORM),所以我通过以下方式实现了这一点:

class Link(Base):
    def parents(self):
        # print self.parent
        # print self.parent_id
        if not self.parent:
            return None
        else:
            return self.parent, self.parent.parents

return 中的嵌套tuples 必须被展平。

PS:AFAIK 只有 PostgreSQL 提供了递归查询的功能,我猜这里需要这个功能。

于 2013-08-21T05:40:59.370 回答