Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL problem

Status
Not open for further replies.

tim55

IS-IT--Management
Sep 13, 2004
137
GB
I have two tables in a master/detail relationship. Is it possible to use a query to join them so that it returns all of the master records and the LAST entry of any detail records associated with it, determined by date?

This would answer the question 'show me all our salesmen, along with details of the last time they visited a customer', assuming that your detail table kept visit info.

I can use MAX() to return just the detail table Date, but I want the rest of the detail table fields as well. I suspect that I could use nested queries, but my version of MySQL does not support them.

Thanks.
 
The next best thing is to create a temporary table, join on it, and then drop it when you are done. This will simulate a subquery.
 
you can do this without a temp table
Code:
select s.name
     , v1.customercompany
     , v1.customercontact
     , v1.datevisited
  from salespeople as s
inner
  join customervisits v1
    on s.id = v1.salesperson_id
inner
  join customervisits v2
    on s.id = v2.salesperson_id
group
    by s.name
     , v1.customercompany
     , v1.customercontact
     , v1.datevisited
having v1.datevisited
     = max(v2.datevisited)
the mysql manual says that most queries that use subqueries can be rewritten as joins, and it's right ;-)

rudy | r937.com | Ask the Expert | Premium SQL Articles
SQL for Database-Driven Web Sites (next course starts May 8 2005)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top