Jan 7, 2004, 11:57 AM
Veteran / Moderator (6956 posts)
Jan 7, 2004, 11:57 AM
Post #3 of 9
Views: 2375
DISTINCT (as well as other functions) behaves differently depending on the MySQL version.
If you think about what DISTINCT means, you'll understand that some of the ways you want it to behave, it can't -- logically.
SELECT DISTINCT(VALUE) will tell you how many DIFFERENT values there are for VALUE. It *obviously* can't return a row, because *which* row with that VALUE would/should it return?
One might argue it should return the most recent row... but again, without an index field or value, which row would that be?
To return DISTINCT rows, you need to do multiple queries, or perhaps a complex/compound query (later versions of MySQL support more of this).
You first select the values with DISTINCT, then pull out the row you want for each distinct value.
This works, for instance, if you have a database of animals, and you want to find out how many cats, dogs, etc other animals you have. If you do a DISTINCT(COUNT SPECIES) then you'd end up with a set of rows: dogs->23, cats->32, birds->21... etc. You would *not* get the row, only the value and count. Select DISTINCT (SPECIES) would return dog, cat, bird, etc.
I played with this for a long time, and eventually gave up. There must be a way to select the most recent (or whatever) row for a DISTINCT field value. I haven't figured it out though <G>.
But, where you say "DISTINCT applies to the whole row" is not quite true. It applies to a specific field, but pretty well ignores the rest of the row -- too much.
One way DISTNCT works, or may work, is if it's used in a table join, where one table is DISTNCTly selected for a value, which is then JOINed to another table.
I have not found a really good explanation, or set of examples for DISTINCT in any of the docs or tutorial sites, or I'd put a reference here.
The above is *not* gospel <G> If someone has a really good explanation, I'd like to know it too.
PUGDOG� Enterprises, Inc.
The best way to contact me is to NOT use Email.
Please leave a PM here.