SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: Distinct

  1. #1
    SitePoint Addict
    Join Date
    Jul 2000
    Location
    North Central AR
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Distinct

    I am trying to understand how DISTINCT is properly used in the select statement. Hard time finding documentation on it, well in plain english anyways.

    I need to select a limited number of rows from my db, and where I wont have any rows with the same site_name

    My code:

    SELECT DISTINCT site_name, link

    This works fine, but when I add another field to the select as:

    SELECT DISTINCT site_name, link, site_id

    I get duplicates for site_name I dont understand why. When using DISTINCT is it suppose to be distinct for all the fields or just the one after DISTINCT? Dont understand why the first one works fine, but not the second?

    Also, is it possible to select at random? Not sure how to write that.

    Thank you in advance.

    ronnie

  2. #2
    SitePoint Addict
    Join Date
    Jul 2000
    Location
    North Central AR
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay a friend helped me a little, guess my problem is I am using Distinct on all three fields. So I need to know how to say DISTINCT for only the site_name field


    ronnie

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,350
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by ronnie
    I am trying to understand how DISTINCT is properly used in the select statement.
    okay, here's the deal with DISTINCT

    it goes after the SELECT keyword

    the purpose of the DISTINCT keyword is to remove duplicate rows

    it sounds like you want aggregation

    aggregation involves GROUP BY which produces a single row for every combination of column values in the GROUP BY

    so you could say, for example, GROUP BY site_name

    then you would get only one row per site_name

    important -- when aggregating, you may place the GROUP BY columns into the SELECT list, but all other expressions in the SELECT list must be aggregate expressions, e.g. count(foo), sum(bar), min(baz), etc.
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Addict
    Join Date
    Jul 2000
    Location
    North Central AR
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you rudy! Works perfectly! I really appreciate it

    ronnie
    The largest selection of PLR Articles on the Planet!
    Many Private Label Rights Products.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •