Add LIMIT to subquery

Add LIMIT to subquery to make ORDER BY work with MariaDB. MariaDB ignores ORDER BY in a subquery unless LIMIT is used. Reference: https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/.  This provides a workaround using LIMIT, but could probably use a further refactor to not use the subquery at all.