'Get the total number of matching records
@param left: left outer joins
@param distinct: count only distinct rows'

def count(self, left=None, distinct=False):

    distinct |= self.distinct
    resource = self.resource
    if (resource is None):
        return 0
    table = resource.table
    vfltr = self.get_filter()
    if ((vfltr is None) and (not distinct)):
        tablename = table._tablename
        ijoins = S3Joins(tablename, self.get_joins(left=False))
        ljoins = S3Joins(tablename, self.get_joins(left=True))
        ljoins.add(left)
        join = ijoins.as_list(prefer=ljoins)
        left = ljoins.as_list()
        cnt = table._id.count()
        row = current.db(self.query).select(cnt, join=join, left=left).first()
        if row:
            return row[cnt]
        else:
            return 0
    else:
        data = resource.select([table._id.name], limit=1, count=True)
        return data['numrows']
