select b.code, name, f.grain, f.fruit
from tc1_birds b
left join (
   select r, code, min(grain) grain, min(fruit) fruit
   from     (
              select count(*) r, g1.code, g1.grain, null fruit
              from tc1_grains g1, tc1_grains g2
              where g1.grain >= g2.grain
                and g1.code = g2.code 
              group by g1.code, g1.grain

              union all

              select count(*) r, f1.code, null, f1.fruit
              from tc1_fruits f1, tc1_fruits f2
              where f1.fruit >= f2.fruit
                and f1.code = f2.code 
              group by f1.code, f1.fruit
           )
   group by code, r
         ) f on b.code=f.code
order by b.code, f.r