我有以下结构:
相册
+----------+----------------------+-------------------+-------------------+--------+
| 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 |
+----------+-------------------+--------+
这里一切顺利。但现在,我想知道是否有可能包含一个 每张专辑的照片都排成一排。对于exaple:
| id_album | name | photos | id_photo | image |
上面我已经从照片表中添加了id_photo
和image
。但我不知道如何触发sql来获得该结果。我很感激你的帮助。
答案 0 :(得分: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;
如果它有任何照片,很可能需要先插入相册的照片。
答案 1 :(得分: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