X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id A999C54FDB for ; Sun, 6 Mar 2005 17:26:21 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 04295-07 for ; Sun, 6 Mar 2005 17:26:16 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id CCACB552D6 for ; Sun, 6 Mar 2005 17:26:14 +0000 (GMT) Received: (qmail 19299 invoked by uid 500); 6 Mar 2005 17:42:01 -0000 Date: Sun, 6 Mar 2005 11:42:01 -0600 From: Bruno Wolff III To: Stefan Weiss Cc: pgsql-sql@postgresql.org Subject: Re: Links between rows in a table Message-ID: <20050306174201.GA19019@wolff.to> Mail-Followup-To: Stefan Weiss , pgsql-sql@postgresql.org References: <422A8A26.1070704@foo.at> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <422A8A26.1070704@foo.at> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.009 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200503/83 X-Sequence-Number: 20562 On Sun, Mar 06, 2005 at 05:42:14 +0100, Stefan Weiss wrote: > > We are currently designing a web-based application in which users can > add other users as "friends". These links are bi-directional, meaning > that when A adds B to his friends, he is automatically one of B's > friends. Eventually we will have to add a feature that shows how A is This doesn't seem like a good idea unless the person getting linked to gets to confirm he wants the link creator as a friend. > I can see several ways how such links could be modeled in a relational > database, but I was wondering if there was some tried-and-true recipe > that would spare me from reinventing the wheel. Putting aside for the > moment everything but the links, the simplest way of connecting users > would be a "friends" table (user_id int, friend_id int). We could get a > user's friends with a simple query like this: > > SELECT friend_id FROM friends WHERE user_id = X > UNION SELECT user_id FROM friends WHERE friend_id = X; It would probably be better to always have either both or neither of the symmetric relationships in the table. You could make a set of triggers to enforce this.