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)");
nathanchere
  • 8,008
  • 15
  • 65
  • 86

1 Answers1

0

A recursive sql function might help. I came across this very specific need, and thank-fully since I was using SQLAlchemy(ORM) I achieved this with something like:

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

The nested tuples in the return will have to be flattened.

PS: AFAIK only PostgreSQL provides the feature of recursive querying which is what I guess is needed here.

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74