开发者

Find package dependencies from database table

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
-----------开发者_Go百科------
      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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜