Try using [noparse]
...
[/noparse] tags. Then your tables won't lose their formatting.
Using b for a book_id, s for a shop_id, and p for a sortorder, I think what you're asking for is:
For a given b, select the shop_id s (if it exists) for which a pair (b,s) exists in the data table, a pair (s,p) exists in the shop_priority table, and p is as small as possible.
Select shop_id from shop_priority where sortorder = (
Select min(sortorder) from shop_priority where shop_id in (
Select shop_id from data where book_id = $b))
That looks horribly inefficient, and only works for one book_id at a time. But it formalises what I said in the previous paragraph, just in case that's a bit hard to follow.