@@ -44,6 +44,9 @@ class QueryExpression:
4444 _heading = None
4545 _support = None
4646
47+ # If the query will be using distinct
48+ _distinct = False
49+
4750 @property
4851 def connection (self ):
4952 """ a dj.Connection object """
@@ -107,7 +110,7 @@ def make_sql(self, fields=None, distinct=True):
107110 :param fields: used to explicitly set the select attributes
108111 """
109112 return 'SELECT {distinct}{fields} FROM {from_}{where}' .format (
110- distinct = "DISTINCT " if distinct else "" ,
113+ distinct = "DISTINCT " if self . _distinct else "" ,
111114 fields = self .heading .as_sql (fields or self .heading .names ),
112115 from_ = self .from_clause (), where = self .where_clause ())
113116
@@ -509,11 +512,9 @@ def cursor(self, offset=0, limit=None, order_by=None, as_dict=False):
509512 """
510513 if offset and limit is None :
511514 raise DataJointError ('limit is required when offset is set' )
515+ sql = self .make_sql ()
512516 if order_by is not None :
513- sql = self .make_sql (distinct = False )
514517 sql += ' ORDER BY ' + ', ' .join (order_by )
515- else :
516- sql = self .make_sql ()
517518 if limit is not None :
518519 sql += ' LIMIT %d' % limit + (' OFFSET %d' % offset if offset else "" )
519520 logger .debug (sql )
@@ -719,6 +720,7 @@ def __and__(self, other):
719720 if not isinstance (other , QueryExpression ):
720721 raise DataJointError ('Set U can only be restricted with a QueryExpression.' )
721722 result = copy .copy (other )
723+ result ._distinct = True
722724 result ._heading = result .heading .set_primary_key (self .primary_key )
723725 result = result .proj ()
724726 return result
0 commit comments