我有一个包含数据架构的专辑库,如下所示
| album_id | album_title |
| 1 | test |
| 2 | test123 |
| 3 | testing |
| img_id | img_albumid | img_full_path | img_album_cover
| 1 | 1 | /blabla/1.jpg | 0
| 2 | 1 | /blabla/2.jpg | 1
| 3 | 1 | /blabla/3.jpg | 0
| 4 | 2 | /blabla/4.jpg | 0
| 5 | 2 | /blabla/5.jpg | 1
| 6 | 3 | /blabla/6.jpg | 0
| 7 | 3 | /blabla/7.jpg | 0
我可以通过交叉加入图像来显示相册。问题是,我想设置专辑封面默认图像。如果用户设置了封面相册,则封面相册将从图像表中显示,但如果未设置封面相册,则仅从img获取任何图像作为封面。到目前为止,此查询有效,但不适用于封面相册
SELECT album_id, album_title, img_full_path
FROM album
LEFT JOIN image ON album_id = img_albumid
WHERE img_albumid != 0
GROUP BY(album_id)
limit 10
如何用php和mysql查询呢?感谢
答案 0 :(得分:2)
使用IFNULL()
功能:
SELECT album_id, album_title, IFNULL(img_full_path, 'default.jpg') as img_full_path
FROM album
LEFT JOIN image ON album_id = img_albumid
WHERE img_albumid != 0
GROUP BY(album_id)
limit 10
来源:http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
您甚至可以使用子查询,该子查询应该只包含一行和一行,如下所示:
SELECT
album_id,
album_title,
IFNULL(img_full_path, (
SELECT
img_full_path
FROM
image
WHERE
(img_albumid = album_id)
AND
NOT (img_full_path IS NULL)
ORDER BY
RAND()
LIMIT 1)
) as img_full_path
FROM
album LEFT JOIN image ON album_id = img_albumid
WHERE
img_albumid != 0
GROUP BY
album_id
LIMIT 10