If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > DISTINCT statement

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-20-10, 02:10
floristboy floristboy is offline
Registered User
 
Join Date: Apr 2010
Posts: 1
DISTINCT statement

Hello,
I am a relative newbie and have been having trouble with the following statement:

SELECT DISTINCT (site), location, locationlink
FROM Links
GROUP BY `site`
ORDER BY RAND()

This does exactly what I require - takes out three fields from the 'Links' table where the 'site' field is unique. Only problem is that it pulls out the same records each time. I want it to pull out a random record from each of the records which have a particular 'site'.
For example there may be 50 records with the site 'london' - I want a random one of those 50 records - not the same one each time.

Can anyone help?

cheers,
Gary
Reply With Quote
  #2 (permalink)  
Old 04-20-10, 06:45
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Quote:
Originally Posted by floristboy View Post
This does exactly what I require - takes out three fields from the 'Links' table where the 'site' field is unique.
sorry, but i have a feeling you don't understand how DISTINCT works

DISTINCT is ~not~ a function, and it applies to all columns in the SELECT clause

you wrote it with parentheses around the first column, thinking that the "distinctness" would be applied to that column...

SELECT DISTINCT (site), location, locationlink

however, in actual fact the "distinctness" applies to all columns...

SELECT DISTINCT (site), location, locationlink

furthermore, you have a GROUP BY clause confounding the issue

GROUP BY site ensures that there is exactly one result row per site, but since the other two columns in your SELECT clause are omitted from the GROUP BY clause (i.e. "hidden" from the GROUP BY clause), the values for those columns are indeterminate

see MySQL :: MySQL 5.1 Reference Manual :: 11.12.3 GROUP BY and HAVING with Hidden Columns
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On