9

次のような有向グラフでエッジを保持するテーブルがあるとします。

CREATE TABLE edges ( 
    from_here int not null, 
    to_there  int not null
)

特定のノードの個別の無向リンクの数を取得するための最も良い方法は何ですか?重複する有向エッジはなく、ノード自体に直接リンクされていません。重複する無向エッジ(となど)を2回カウントすることは避けたいだけ(1,2)です(2,1)

これは機能しますが、私にはNOT IN悪臭がします:

SELECT COUNT(*)
FROM edges
WHERE from_here = 1
   OR (to_there = 1 AND from_here NOT IN (
        SELECT to_there 
        FROM edges 
        WHERE from_here = 1
   ))

これにはPostgreSQL固有のソリューションで十分です。

4

3 に答える 3

7

すべてのエッジに逆数があった場合(たとえば、(1,2)存在する場合は存在する(2,1)必要があります)、次のようにリストを単純に絞り込むことができます。

 Select Count(*)
 From edges
 Where from_here < to_here
    And from_here = 1

相互エッジが常に存在すると想定できない場合は、Except述語を使用できます。

Select Count(*)
From    (
        Select from_here, to_there
        From edges
        Where from_here = 1
            Or to_there = 1
        Except
        Select to_there, from_here
        From edges
        Where from_here = 1
        ) As Z
于 2011-03-10T20:01:48.340 に答える
6
select count(*) from (
  select to_there from edges where from_here = 1
  union
  select from_here from edges where to_there = 1
) as whatever
于 2011-03-10T19:54:33.687 に答える
1
SELECT COUNT(DISTINCT CASE to_here WHEN 1 THEN from_here ELSE to_here END)
FROM edges
WHERE from_here = 1
   OR to_here = 1
/* or WHERE 1 IN (from_here, to_here) */
于 2012-04-27T10:07:56.663 に答える