views:

12

answers:

1

I have two tables in a database, one lists package and one lists dependencies:

packages

id | name
---------
 0 | xorg
 1 | gnome-session
 2 | gnome-panel
 3 | gnome-mixer-applet
 4 | gnome-media

depends

package | depends
-----------------
      1 | 0
      2 | 1
      3 | 2
      4 | 2

Obviously, if I want to find out what a package depends on, I can do:

SELECT *
  FROM packages
 INNER JOIN depends
    ON packages.id = depends.package
 WHERE packages.id = @somenumber

The problem is that this only gives me one level of dependencies (4 depends on 2, but it also depends on packages 1 and 0). Is there a way to get all of the dependencies without just running similar SELECTs in a loop?

I'd prefer that it works in SQLite, but I'll use a different database if I need to (as long as it's free and available on Linux).

+1  A: 

PostgreSQL is the only open-source RDBMS that supports recursive queries. For example, you could run this:

WITH RECURSIVE package_deps(id) AS (
  SELECT d.package FROM depends d WHERE d.package = @startingnumber
  UNION ALL
  SELECT d.package FROM depends d JOIN package_deps pd ON d.depends = pd.id
)
SELECT p.* FROM package_deps pd JOIN packages p USING (id);

SQLite has no support for recursive queries, but there are several other solutions for managing hierarchical data in more plain SQL. See my presentation Models for Hierarchical Data with SQL and PHP.

Bill Karwin
Very interesting. I'll have to try some of the patterns in your presentation.
Brendan Long
I also cover tree-like data, and many other topics, in my new book *SQL Antipatterns* :-) http://www.pragprog.com/titles/bksqla/sql-antipatterns
Bill Karwin