mpen
mpen

Reputation: 283023

MySQL query: Get all album covers

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?

Upvotes: 0

Views: 194

Answers (2)

tekBlues
tekBlues

Reputation: 5793

select * from album, photos 
where album_id=albums.id  
and albums.user_id='user_id'
and photos.id = (select id from photos where 
album_id = album.id order by position LIMIT 1)

Upvotes: 1

cgmack
cgmack

Reputation: 19

You could use ORDER BY and LIMIT your results to the first row like so:

SELECT photos.* 
FROM 
  albums, photos
WHERE
  photos.album_id=albums.id
  AND albums.user_id=%s
ORDER BY
  photos.position ASC
LIMIT 1

Upvotes: 0

Related Questions