mysql query with 1 derived table and 1 inner join takes forever to load
(Need formatting not available in a Comment.)

This is ambiguous:

FROM deal_buildings AS db2
WHERE db2.deal_id = n.id
  AND n.main_member_id = 79
  AND db.status in (11,12,13,20,21)
ORDER BY status DESC              -- Is this in `db` or `db2`?  QUALIFY!


IF(blah, true, false) can be shortened to just (blah)