OK, I got this working for me, with a default image in case the query doesn’t return anything.
{if segment_1 != ""}
{exp:query sql="SELECT entry_id AS headerpic
FROM exp_gallery_entries
WHERE gallery_id = 3
AND cat_id = 4
AND custom_field_one = '{segment_1}'"}
{if no_results}
{exp:gallery:entries dynamic="off" gallery="header_images" entry_id="26"}
{image_url}
{/exp:gallery:entries}
{/if}
{exp:gallery:entries dynamic="off" gallery="header_images" entry_id="{headerpic}"}
{image_url}
{/exp:gallery:entries}
{/exp:query}
{/if}
In English: if segment_1 is there, select from galleries (in the right category and gallery) where custom_field_one matches the segment, and return the ID of that pic. If there was no result, who the default header image. If there was a result, then by all means, show that pic!
You may not need the outer if statement, and I’m sure your gallery and category numbers will be different. Hope that helps you out!