join queries

Started by David M. Kaplanabout 25 years ago2 messagesgeneral
Jump to latest
#1David M. Kaplan
dkaplan@bio.puc.cl

Hi,

I have a query which seems like it should easy, but isnt. I have two
tables, a and b that look like this:

a)

id | c1
--+--
1 | a
2 | b
3 | c

b)

id | c2
--+--
2 | b

and I would like to do a query which returns

id | c1 | c2
--+--+--
1 | a |
2 | b | b
3 | c |

The simplest thing I could find was

SELECT a.*, (SELECT b.c2 WHERE a.id=b.id) AS c2;

This works, but is extremely slow for more complex examples. Is there a
better way to do this in postgresql?? I think MS Access has inner and
outer joins to solve this problem. Is there a postgresql equivalent?

Thanks for the help.

David Kaplan

#2Oliver Elphick
olly@lfix.co.uk
In reply to: David M. Kaplan (#1)
Re: join queries

"David M. Kaplan" wrote:

Hi,

I have a query which seems like it should easy, but isnt. I have two
tables, a and b that look like this:

a)

id | c1
--+--
1 | a
2 | b
3 | c

b)

id | c2
--+--
2 | b

and I would like to do a query which returns

id | c1 | c2
--+--+--
1 | a |
2 | b | b
3 | c |

The simplest thing I could find was

SELECT a.*, (SELECT b.c2 WHERE a.id=b.id) AS c2;

This works, but is extremely slow for more complex examples. Is there a
better way to do this in postgresql?? I think MS Access has inner and
outer joins to solve this problem. Is there a postgresql equivalent?

SELECT a.id, c1, c2 FROM a LEFT OUTER JOIN b ON a.id = b.id

This requires PostgreSQL 7.1

--
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 as many as received him, to them gave he power to
become the sons of God, even to them that believe on
his name." John 1:12