Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id F2094C7DB10 for ; Mon, 19 Mar 2012 11:27:30 -0300 (ADT) Received: from gwmta.wicourts.gov ([165.219.244.99] helo=gw.wicourts.gov) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1S9dYV-0000Z8-TE for pgsql-performance@postgresql.org; Mon, 19 Mar 2012 14:27:30 +0000 Received: from Courts-MTA by gw.wicourts.gov with Novell_GroupWise; Mon, 19 Mar 2012 09:27:13 -0500 Message-Id: <4F66FBEA020000250004640C@gw.wicourts.gov> X-Mailer: Novell GroupWise Internet Agent 8.0.2 Date: Mon, 19 Mar 2012 09:27:06 -0500 From: "Kevin Grittner" To: "Robert Poor" , "Scott Marlowe" , Subject: Re: slow self-join query References: In-Reply-To: Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Content-Disposition: inline X-Pg-Spam-Score: -4.2 (----) X-Archive-Number: 201203/128 X-Sequence-Number: 46578 Robert Poor wrote: > among users that follow leader 321, who are the most widely > followed leaders?", or more formally, find all the users that are > followers of user 321 (via inner join on F1) Of those users, > tally up their leaders so we know which leaders are most popular. It sounds like you're looking for something like this: SELECT leader_id, count(*) as count FROM user_associations x WHERE exists ( SELECT * FROM user_associations y WHERE y.follower_id = x.follower_id AND y.leader_id = 321 ) GROUP BY leader_id ; > create_table "user_associations", :force => true do |t| > t.integer "follower_id" > t.integer "leader_id" > end I don't really know what that means. In the future, it would make things easier on those who are trying to help if you either post the SQL form or go into psql and type `\d tablename`. -Kevin