如何从数据库中获取唯一记录?

时间:2013-01-21 16:38:02

标签: mysql

这是我的表结构

album
id ---- albumname
1   General
3   Sports
9   Activities
gallery
id --- ablumid--- image_thumb  --              image_full
1   1   uploads/1358401616.jpg  uploads/thumbs/thumb_1358401616.jpg
2   1   uploads/1358401641.jpg  uploads/thumbs/thumb_1358401641.jpg
3   1   uploads/1358402071.jpg  uploads/thumbs/thumb_1358402071.jpg
4   3   uploads/1358402334.jpg  uploads/thumbs/thumb_1358402334.jpg

问题是我有太多的图像用于烧烤画廊。

这是我的mysql查询

SELECT DISTINCT gl.catid as gallery_cat_id, ab.albumname,gl.imagest 
FROM albums as ab 
INNER JOIN gallery as gl  ON ab.id=gl.catid 
order by ab.albumname ASC

结果如下

gallery_id  albumname   image_full
38      Activities       uploads/thumbs/thumb_1358424428.jpg
41      Activities       uploads/thumbs/thumb_1358424483.jpg
40      Activities       uploads/thumbs/thumb_1358424468.jpg
39      Activities       uploads/thumbs/thumb_1358424446.jpg

查询显示来自图库表的所有记录我在查询中添加了DISTINCT,但它无效。 谁能告诉我我错过了什么?

1 个答案:

答案 0 :(得分:0)

如果您只需要每张专辑的单张图片(无论如何),您可以使用GROUP BY子句按专辑ID进行分组:

SELECT gl.catid as gallery_cat_id, ab.albumname, gl.imagest 
FROM
  albums as ab 
  INNER JOIN gallery as gl
  ON ab.id=gl.catid 
GROUP BY ab.id
order by ab.albumname ASC