1

我有以下结构:

专辑

+----------+----------------------+-------------------+-------------------+--------+
| id_album | description          | name              | url               | status |
+----------+----------------------+-------------------+-------------------+--------+
|        1 | el primer album      | primer album      | primer-album      |      1 |
|        2 | El album del viernes | album del viernes | album-del-viernes |      1 |
|        3 | dasdas               | album 3           | album             |      1 |
+----------+----------------------+-------------------+-------------------+--------+

照片

+----------+-------------+-----------------------------+-------+---------+
| id_photo | description | image           | album | published           |
+----------+-------------+-----------------------------+-------+---------+
|        1 |             | 1_1361894_n.jpg |     1 | 2012-05-24 13:36:36 |
|        2 |             | 1_537885_n.jpg  |     1 | 2012-05-24 13:36:39 |
|        3 |             | 17227078_n.jpg  |     1 | 2012-05-24 13:36:40 |
|        4 |             | _6891390_n.jpg  |     1 | 2012-05-24 13:36:40 |
|        5 |             | 15743568_n.jpg  |     1 | 2012-05-24 13:36:44 |
|        6 |             | -sol.jpg        |     2 | 2012-06-29 09:55:23 |
|        9 |             | fondo2.gif      |     2 | 2012-08-13 16:46:10 |
|        8 |             | barra.gif       |     1 | 2012-07-10 12:13:04 |
+----------+-------------+-----------------+-------+---------------------+

实际上,我正在选择包含至少一张照片的所有相册:

SELECT a.id_album, a.name, count(p.id_photo) AS photos 
FROM album a
LEFT JOIN photo p ON a.id_album = p.album 
GROUP BY a.id_album 
HAVING photos > 0;

+----------+-------------------+--------+
| id_album | name              | photos |
+----------+-------------------+--------+
|        1 | primer album      |      6 |
|        2 | album del viernes |      2 |
+----------+-------------------+--------+

这里一切顺利。但是现在,我想知道是否可以将每个相册的一张照片包含在行中。例如:

| id_album | name | photos | id_photo | image |

看上面我已经包括id_photoimage照片表。但我不知道如何触发 sql 以获得该结果。我很感激你的帮助。

4

2 回答 2

3
SELECT a.id_album, a.name, count(p.id_photo) AS photos, p.id_photo, p.image 
FROM album a
LEFT JOIN photo p ON a.id_album = p.album 
GROUP BY a.id_album 
HAVING photos > 0;

如果它有任何照片,它很可能会首先插入相册的照片。

于 2012-11-21T15:28:34.193 回答
2
SELECT  a.*, b.*, c.totalCount
FROM    Album a
        INNER JOIN Photo b
            ON a.id_album = b.album
        INNER JOIN
        (
            SELECT  album, 
                    MAX(published) maxDate,
                    COUNT(*) totalCount
            FROM    Photo
            GROUP BY album
        ) c ON b.album = c.album AND
                b.published = c.maxDate
WHERE   c.totalCount > 1
于 2012-11-21T15:33:06.337 回答