Thread: distinct, count
View Single Post

  #4 (permalink)  
Old 12-02-2005
Bill Karwin
 
Posts: n/a
Default Re: distinct, count

Frances wrote:
> hello, is there something wrong w/this query?
>
> SELECT DISTINCT(tbuser.fk_userid), COUNT(tbuser.fk_userid) AS
> cuserid........
>
> I'm getting this error: Unknown table 'tbuser' in field list
> (table is there, use in other queries..)


I can't tell exactly the problem, because I don't know the rest of your
query. Is tbuser in the FROM clause of your SELECT? Are you querying a
view which itself references tbuser? If so, you should reference the
view name in this query, not the underlying table name. Or is the above
query your definition of the view? A few more details are needed to
diagnose this one.

Another problem is that a leading DISTINCT in the select-list is not a
function; it's a modifier to the whole query. You don't use it like:
DISTINCT(expr). You use it like:
SELECT DISTINCT field(s) ...
It applies to _all_ the fields you are selecting.

A different context for DISTINCT is that which is used inside a COUNT()
function. This is not the same DISTINCT operation as mentioned above.
Again, it is not used in the syntax as though it were a function. You
can use it like:
COUNT(DISTINCT expr)
It applies only to its expression argument, for purposes of calculating
the COUNT.

DISTINCT can be used similarly to modify the expression inside SQL
aggregate functions AVG(), MIN(), MAX(), and SUM(), and the special
MySQL extension GROUP_CONCAT().

It is a bit muddy, because expr can have parentheses around it; that is,
"2+2" and "(2+2)" are both legal and equivalent expressions. So
COUNT(DISTINCT (expr)) is syntactically legal, although the inner
parentheses are not necessary.

Regards,
Bill K.
Reply With Quote