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 CD8A755012 for ; Mon, 7 Mar 2005 16:00:14 +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 08502-07 for ; Mon, 7 Mar 2005 16:00:10 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id 75FF256367 for ; Mon, 7 Mar 2005 16:00:07 +0000 (GMT) Received: (qmail 7382 invoked by uid 500); 7 Mar 2005 16:15:55 -0000 Date: Mon, 7 Mar 2005 10:15:55 -0600 From: Bruno Wolff III To: PFC Cc: Stefan Weiss , pgsql-sql@postgresql.org Subject: Re: Links between rows in a table Message-ID: <20050307161555.GA3643@wolff.to> Mail-Followup-To: PFC , Stefan Weiss , pgsql-sql@postgresql.org References: <422A8A26.1070704@foo.at> <20050306174201.GA19019@wolff.to> <422B4B9A.8020606@foo.at> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: 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/110 X-Sequence-Number: 20589 On Sun, Mar 06, 2005 at 20:26:50 +0100, PFC wrote: > >>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. > > Because your relation is symmetric, you should not name them "user" > and "friend". > The duplication is useless if you add a constraint : see this > > create table friendship ( > user_id_1 integer references ... on delete cascade, > user_id_2 integer references ... on delete cascade, > > CHECK( user_id_1 < user_id_2 ) > ); The trouble with this approach is that for some ways of using this data you will need to worry about the ordering of of the values. The advantage of this method is that the space needed to store the data is half of what is needed to store both pairs for each friendship. > user_id_1 < user_id_2 means : > - a user can't be his own friend > - only one row per friend > - when you want to know if A is friend of B, no need to make two > selects, just select where user_id_1 = min(user_id_A, user_id_B) AND > user_id_2 = max(user_id_A, user_id_B) Note that you can't literally use 'min' and 'max' as above, as those functions don't do that. You could use 'case' to do that.