I am LAZY bones?
AN ancient AND boring SITE

oracle里循环搜索父子关系的键

想象一下,如果有一张oracle里的表,存着的是一个linux系统当前的进程信息,有ID、父ID、进程名之类的字段,如果给定一个进程ID,要查这个进程的所有父进程(包括爷爷进程等)的ID,sql改怎么写?这就要用到 CONNECT BY PRIOR … START WITH 子句了。
下面就是这样的一个例子:

--原先的表大致是这样的:
SELECT id, parentid FROM the_table WHERE id IN (14976, 14975);
        ID   PARENTID
---------- ----------
     14975      14657
     14975      14658
     14975      14992
     14975      15047
     14976      14975
--要查所有的父进程,这么干:
SELECT DISTINCT id FROM the_table CONNECT BY PRIOR parentid = id START WITH id = 14976;
        ID
----------
         1
       110
       127
       130
       155
       163
     12930
     13812
     14656
     14657
     14658
     14949
     14950
     14951
     14975
     14976
     14992
     15047

最后修改时间: 2010年08月12日 09:07

本文章发表于: 2010年08月12日 09:07 | 所属分类:数据平台. | 您可以在此订阅本文章的所有评论. | 您也可以发表评论, 或从您的网站trackback.

9 个评论 关于: “oracle里循环搜索父子关系的键”

  1. SomeOne 在 2010年08月12日 10:41 说:回复

    SQL Server 就只能写递归函数了…

  2. young001 在 2010年08月12日 17:30 说:回复

    这是板凳,是的,就是板凳:-)

  3. xiooli 在 2010年08月12日 22:24 说:回复

    SELECT parentid FROM the_table WHERE id IN (SELECT id FROM the_table WHERE id = 14976 LIMIT 1);

    行不行呢?

    • abettor 在 2010年08月13日 08:50 说:回复

      楼上的方式只能多查一级,而且语句还有点小错误。
      这个功能确实威武!

  4. Dig 在 2010年08月13日 14:39 说:回复

    父进程不是只有一个吗?怎么14975有那么多个爹?

    • bones7456 在 2010年08月13日 14:59 说:回复

      我只是拿进程举个例子,这里的数据并不是进程信息。

      • Dig 在 2010年08月13日 16:52 说:回复

        骨头写出了新OS,支持多父进程。哈哈哈

  5. MeaCulpa 在 2010年09月14日 13:22 说:回复

    self join大家都有, 但这个确实方便….

  6. Cage 在 2025年06月17日 02:57 说:回复

    Dear Founder,

    An active investor we represent is now reviewing investment ready business ideas across all sectors no matter your industry or stage. What matters most is a compelling, scalable idea with strong execution potential.

    Available Funding Options:
    • 3% annual interest rate
    • No early repayment penalties
    • Convertible loan option available – convert to 10–15% equity after 2 years (optional)

    Whether you’re building the next big tech platform, expanding a niche brand, or launching a bold new venture, now’s your chance to access smart capital on founder-friendly terms.

    Simply send in your pitch deck or business plan to start the conversation. If your idea is solid, we’re ready to move.

    Let’s help you bring your vision to life.

    Yours Truly,
    Chary Marshal
    Investment Consultant/Strategist
    Email: charyl74@akirapowered.com

发表评论