MySQL查询:获取所有专辑封面

时间:2009-06-12 00:29:01

标签: mysql

我需要一些帮助来制定这个查询。我有两个(相关的)表,我将在此处转储以供参考:

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 ;

现在我想从某个用户拥有的每张专辑中抓取第一张照片(最低位置#)。

以下是我正在尝试的内容:

SELECT * FROM albums JOIN photos ON photos.album_id=albums.id WHERE albums.user_id=%s GROUP BY album_id HAVING min(position)

但是having子句似乎没有效果。有什么问题?

2 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

您可以使用ORDER BY并将结果限制在第一行,如下所示:

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