code: def _construct_select_query(**filter_definition):
      table_name = filter_definition.pop('table')
      distinct = filter_definition.pop('distinct', False)
      select_count = filter_definition.pop('count', False)
      if distinct and select_count:
          raise UnsupportedDefinitionError('SELECT (DISTINCT ...) is not supported')
      if select_count and 'select' in filter_definition:
          raise UnsupportedDefinitionError('SELECT COUNT(columns) is not supported')
      if 'joins' in filter_definition:
          join_definitions = filter_definition.pop('joins')
          if not isinstance(join_definitions, (tuple, list)):
              join_definitions = (join_definitions,)
          filter_definition['joins'] = []
          for join_def in join_definitions:
              filter_definition['joins'].append(_expand_join(join_def))
      if 'where' in filter_definition:
          for key, value in filter_definition['where'].items():
              if is_filter_query(value):
                  sub_query = value.pop(DEFAULT_FILTER_KEY)
                  if value:
                      raise ParsingInputError("Unknown keys for sub-query provided: %s" % value)
                  filter_definition['where'][key] = mosql_raw('( {} )'.format(_construct_select_query(**sub_query)))
              elif isinstance(value, str) and value.startswith('$') and QUERY_REFERENCE.fullmatch(value[1:]):
                  filter_definition['where'][key] = mosql_raw('"{}"'.format('"."'.join(value[1:].split('.'))))
      raw_select = select(table_name, **filter_definition)
      if distinct:
          raw_select = raw_select.replace('SELECT', 'SELECT DISTINCT', 1)
      if select_count:
          raw_select = raw_select.replace('SELECT *', 'SELECT COUNT(*)', 1)
      return raw_select