Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL JOIN, GROUP BY, ORDER BY

Demonstração do SQLFiddle

select products.id,
       coalesce(t1.mid,t2.mid) as image_id      

from products
left join (select min(id) mid,product_id 
                  from images where `default`=1
                  group by product_id ) t1
        on products.id=t1.product_id
left join (select min(id) mid,product_id 
                  from images where `default`=0
                  group by product_id ) t2
        on products.id=t2.product_id