douzhenao6515 2014-09-27 23:19
浏览 51
已采纳

显示所有照片库相册的专辑封面

I have a photo gallery where I allow the user to create individual photo albums. I can display the name of each album like this.

$album = DB::getInstance()->query("SELECT `album_id`,`album_date`,`album_title` FROM `albums` ORDER BY `album_date` DESC");

What I'm trying to do is add a cover photo for each album, but can't seem to get my query correct. This is what I'm trying.

$album = DB::getInstance()->query("SELECT
albums.album_id,
albums.created,
albums.album_date,
albums.album_title,
gallery.file_name,
gallery.id,
gallery.album_id
FROM
albums
INNER JOIN gallery ON gallery.album_id = albums.album_id ORDER BY gallery.id DESC ;");

This is the result I get:

enter image description here

This is the result I'm trying to achieve:

enter image description here

I want each album name displayed with the last photo from each album as the cover photo.

If I add a LIMIT of 1 to my query, only one album is shown.

Here are my tables that are Joined together by a Foreign Key.

Albums Table:

enter image description here

Gallery Table:

enter image description here

Any solution to get this working would be much appreciated.

  • 写回答

5条回答 默认 最新

  • dthswrp84966 2014-09-28 05:24
    关注

    You can select the most recent image in each album using the following query:

    SELECT album_id, MAX(id) id
    FROM gallery
    GROUP BY album_id
    

    Alternatively, you can select a random image in each album like this:

    SELECT g.album_id, (
        SELECT id FROM gallery g2
        WHERE g2.album_id = g.album_id
        ORDER BY RAND()
        LIMIT 1
    ) id
    FROM gallery g
    GROUP BY g.album_id
    

    Either of the above queries could be plugged into a complete query:

    SELECT a.album_id, a.created, a.album_date, a.album_title,
           g.file_name, g.id, g.album_id
    FROM albums a
    INNER JOIN (
        # above query goes here
    ) alb_img USING (album_id)
    INNER JOIN gallery g ON g.id = alb_img.id
    ORDER BY a.album_date DESC;
    

    If you'd like to select empty albums as well as those containing one or more images change the INNER JOINs to LEFT JOINs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式