Wrox Programmer Forums
Go Back   Wrox Programmer Forums > PHP/MySQL > MySQL
|
MySQL General discussion about the MySQL database.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the MySQL section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old September 13th, 2006, 03:46 AM
pnj pnj is offline
Registered User
 
Join Date: Sep 2006
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default help with mysql subquery

If this should be posted in another forum, please let me know.

I am having difficulty structuring a subquery using the MAX() operation.

I have a table 'visit' with the following fields:

primary_key, parent_id, vdate, answer

Each row is linked to a parent table via parent_id, and there can be multiple rows for each parent_id. I want my query to give me the contents of the 'answer' field for the most recent date for each parent_id.

This select query gets the max visit date, but the answer field is not necessarily from the same row as the max visit date, so this is not the answer:
SELECT max(visit_date), answer from visit group by parent_id;

This subquery returns what appears to be the correct result, but takes mysql 2 minutes and 30 seconds to compute:

SELECT answer FROM visit WHERE (parent_id, vdate)=ANY (SELECT parent_id, MAX(vdate) FROM visit GROUP BY parent_id);

It doesn't seem like that complicated a request, especially since I am only talking about 2500 rows in the visit table, and 500 rows returned from the subquery.

Can someone recommend a more efficient approach?

Thanks,

Paul
 
Old October 24th, 2006, 05:42 PM
Friend of Wrox
 
Join Date: Dec 2003
Posts: 488
Thanks: 0
Thanked 3 Times in 3 Posts
Default

Does doing a join help?

Code:
SELECT max(visit_date), answer 
  FROM visit,parent 
 WHERE parent.id = parent_id
--
Don't Stand on your head - you'll get footprints in your hair
                                           http://charlieharvey.org.uk
                                              http://charlieharvey.com





Similar Threads
Thread Thread Starter Forum Replies Last Post
Subquery debbiecoates SQL Server 2000 4 June 25th, 2008 03:49 AM
PHP/MySQL Subquery Problem gfackler MySQL 1 April 18th, 2007 11:31 PM
Do i have to use a subquery, if yes then how? code_lover SQL Language 2 January 2nd, 2007 02:22 PM
Help...subquery problem Twistdmojo Classic ASP Databases 4 September 14th, 2006 11:45 AM
subquery khansa MySQL 1 February 21st, 2006 02:49 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.