Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Need help with complex SQL Select Query

Hi all-

On my current project, I've come across a situation with the database (MS Access) which has me stuck.

I have 2 tables. One is a list of film productions. It has (among others) a ProducerID column and a CoProducerID column.
The other table is named Directory, and lists names, addresses, etc. It has a DirectoryID column, and a DisplayName column.

Here's the problem: in the Productions table, BOTH the ProducerID column and the CoProducerID column are related to the DirectoryID column in the Directory table. In other words, some records in the Directory table are for Producers, and some are for Co-Producers.
I need to create a SQL SELECT query which will pull the DisplayName column for the Producers AND for the Co-Producers!

It's easy enough to do a LEFT OUTER JOIN to pull the DisplayName for the Producer, joining the ProducerID column with the DirectoryID. The problem is, how to get the DisplayName for the CoProducerID column??

I can't join the same 2 tables twice, right?

If anyone can help, I would greatly appreciate it...

Thanks,

-Andrew
[1162 byte] By [Andrew Cushen] at [2007-11-11 10:00:25]
# 1 Re: Need help with complex SQL Select Query
Boy, this was obvious once I thought about it from a different angle!

Basically, what I did was create 2 queries.

The first query included all the columns from the Productions table, and the first join to the Directory table, to grab the Producer's DisplayName.

The second query pulled all the columns [by name, NOT using "*"] from the first query, then added the second join to the Directory table, to pull the CoProducer's DisplayName.

Once I remembered that you can "query a query", it was a snap...

I am still interested to know if there is a way to do this in one query that works; possibly by aliasing the second reference to the Directory table using "AS"?

-Andrew
Andrew Cushen at 2007-11-11 23:43:31 >
# 2 Re: Need help with complex SQL Select Query
I've never worked with Access, so your milage may vary, but in this case, you should generally join the table twice.

SELECT p.*, d1.DisplayName AS ProducerName, d2.DisplayName AS CoProducerName
FROM productions AS p
LEFT JOIN directory AS d1 ON ProducerID = d1.DirectoryID
LEFT JOIN directory AS d2 ON CoProducerID = d2.DirectoryID
megabassjosh at 2007-11-11 23:44:36 >