aew_78
02-13-2008, 02:41 AM
Hello,
I have a table with the following general format:
CREATE TABLE `table_name` (
`id` int(10) unsigned NOT NULL default '0',
`date` date NOT NULL default '0000-00-00',
`value1` double default NULL,
`value2` double default NULL,
PRIMARY KEY (`id`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
What I want to do is to retrieve results from this table where the most recent values for the ids are returned with only one returned record per id.
In MySql this works:
SELECT id, date, value1, value2 FROM (SELECT * FROM table_name WHERE date < '2005-01-12' ORDER BY date desc) rt GROUP BY id;
This generates the proper result set for me with only one result per id and that result being the most recent record from the date specified.
But I have heard on some forums and in tutorials that this is not the correct use of the group by clause and that mysql accepts this unconventional use of group by without generating warnings that other database servers would generate because of the lack of aggregate functions for the fields.
My question is this, how would such a query be performed without the use of the group by clause or could it be done without it? I would prefer my sql statements to be as portable as possible but I really need this functionality.
Thanks for any help you can give me on this matter.
I have a table with the following general format:
CREATE TABLE `table_name` (
`id` int(10) unsigned NOT NULL default '0',
`date` date NOT NULL default '0000-00-00',
`value1` double default NULL,
`value2` double default NULL,
PRIMARY KEY (`id`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
What I want to do is to retrieve results from this table where the most recent values for the ids are returned with only one returned record per id.
In MySql this works:
SELECT id, date, value1, value2 FROM (SELECT * FROM table_name WHERE date < '2005-01-12' ORDER BY date desc) rt GROUP BY id;
This generates the proper result set for me with only one result per id and that result being the most recent record from the date specified.
But I have heard on some forums and in tutorials that this is not the correct use of the group by clause and that mysql accepts this unconventional use of group by without generating warnings that other database servers would generate because of the lack of aggregate functions for the fields.
My question is this, how would such a query be performed without the use of the group by clause or could it be done without it? I would prefer my sql statements to be as portable as possible but I really need this functionality.
Thanks for any help you can give me on this matter.