简体   繁体   中英

MySQL SELECT query get record if is_default = 1 otherwise is_default = 0?

My image table look like this:

id     product_id     image         is_default

1      11             test.jpg      0
2      11             make.jpg      0
3      11             tkae.jpg      1
4      11             value.jpg     0
5      11             mcate.jpg     0

I want to fetch a default image if is_default 1 is not exists the fetch first image. I try this query but not success.

SELECT *
FROM `images`
WHERE `product_id` = '11'
GROUP BY `product_id`
ORDER BY `is_default` DESC

Can anyone help me to write that query.

A simpler

SELECT *
FROM `images`
WHERE `product_id` = '11'
ORDER BY `is_default` DESC
LIMIT 1

should work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM