I have a album gallery with data schema like below
| 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
I can display the album by cross join the image. The issue is, I want to set album cover default image. The cover album will display from image table if user has set it but just get any image from img as cover if the cover album not set. So far this query works, but not for cover album
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
How to do it with php and mysql query? Thanks
Use IFNULL()
function:
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
Source: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
You might even use subquery, which should contain only one row and column, like this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.