select * from table
where prod=1111
and (
(show_main='Y')
or
( show_main='N' and not exists( select * from table where prod=1111 and show_main='Y'))
)
order by rand() )
select prd_id ,case when sum(case show_main when 'y' then 1 else 0 end)>0 then 'y' else 'n' end as show_main
from prd_pic where prd_id='1111111'
Code (SQL)
select prd_pic.* ,case when tb_y.prd_id is null then 'n' else 'y' end as show_main2 from prd_pic
left join (select prd_id from prd_pic where show_main='y' and prd_id='1111111' limit 1) as tb_y on prd_pic.prd_id=tb_y.prd_id
where prd_pic.prd_id='1111111'