I need some help formulating this query. I have two (relevant) tables, which I will dump here for reference:
CREATE TABLE IF NOT EXISTS `albums` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT 'owns all photos in album',
`parent_id` int(11) DEFAULT NULL,
`left_val` int(11) NOT NULL,
`right_val` int(11) NOT NULL,
`name` varchar(80) COLLATE utf8_unicode_ci NOT NULL,
`num_photos` int(11) NOT NULL,
`date_created` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `parent_id` (`parent_id`,`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `photos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`album_id` int(11) NOT NULL,
`filename` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`num_views` int(11) NOT NULL DEFAULT '0',
`date_uploaded` int(11) NOT NULL,
`visibility` enum('friends','selected','private') COLLATE utf8_unicode_ci NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=26 ;
Now I want to grab the first photo (lowest position #) from each album owned by a certain user.
Here's what I'm trying:
SELECT * FROM albums JOIN photos ON photos.album_id=albums.id WHERE albums.user_id=%s GROUP BY album_id HAVING min(position)
But the having clause doesn't seem to have an effect. What's the problem?