Received: from anchor-post-31.mail.demon.net (anchor-post-31.mail.demon.net [194.217.242.89]) by postgresql.org (8.11.3/8.11.1) with ESMTP id f3AK5t865588 for ; Tue, 10 Apr 2001 16:05:55 -0400 (EDT) (envelope-from olly@lfix.co.uk) Received: from lfix.demon.co.uk ([158.152.59.127] helo=linda.lfix.co.uk) by anchor-post-31.mail.demon.net with esmtp (Exim 2.12 #1) id 14n4OZ-0008Fe-0V; Tue, 10 Apr 2001 21:05:47 +0100 Received: from lfix.co.uk (olly@localhost [127.0.0.1]) by localhost (8.11.3/8.11.3/Debian 8.11.2-1) with ESMTP id f3AK5k200681; Tue, 10 Apr 2001 21:05:46 +0100 Message-Id: <200104102005.f3AK5k200681@linda.lfix.co.uk> X-Mailer: exmh version 2.3.1 01/18/2001 (debian 2.3.1-1) with nmh-1.0.4+dev X-URL: http://www.lfix.co.uk/oliver X-face: "xUFVDj+ZJtL_IbURmI}!~xAyPC"Mrk=MkAm&tPQnNq(FWxv49R}\>0oI8VM?O2VY+N7@F- KMLl*!h}B)u@TW|B}6 cc: pgsql-sql@postgresql.org Subject: Re: a select statement that sometimes joins In-reply-to: Message from Mark Stosberg of Tue, 10 Apr 2001 14:13:34 EDT. Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Date: Tue, 10 Apr 2001 21:05:45 +0100 From: "Oliver Elphick" X-Archive-Number: 200104/144 X-Sequence-Number: 2492 Mark Stosberg wrote: > > > >Here's a situation I've run into more than once with SQL: > >I want to select all the rows in a table that match a criteria, where one >of the criteria is possibly having a related entry in a second table. For >my example, lets say I have table named 'messages' and another named >'message_attachments'. The former has a primary key of msg_id, the latter >also contains msg_id, and has an attachment_id as it's primary key. > >This statement shows me all the messages that also have attachments: > >SELECT > messages.msg_id, > message_attachments.attachment_id > FROM messages,message_attachments > WHERE messages.msg_id = message_attachments.msg_id; > >But I want a statement that says: "Show me all the messages, and include >information about an attachment if they have one" SELECT m.msg_id, a.attachment_id FROM messages AS m LEFT OUTER JOIN message-attachments AS a ON m.msg_id = a.msg_id; This requires 7.1 for the LEFT OUTER JOIN. In 7.0.3 you could do it with a UNION. -- Oliver Elphick Oliver.Elphick@lfix.co.uk Isle of Wight http://www.lfix.co.uk/oliver PGP: 1024R/32B8FAA1: 97 EA 1D 47 72 3F 28 47 6B 7E 39 CC 56 E4 C1 47 GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C ======================================== "But seek ye first the kingdom of God, and his righteousness; and all these things shall be added unto you." Matthew 6:33