Query to select unique combination of two columns

Discussion in 'PHP' started by pmf123, Jun 25, 2010.

  1. #1
    I have a database with first and last names for a specific area.

    The first name is in one column and the surname is in another column.

    I am trying to pull all the unique name combinations

    is there one query to do it?

    Thanks
     
    pmf123, Jun 25, 2010 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    You can do select distinct

    SELECT DISTINCT first_name, last_name FROM table ORDER BY first_name;
    Code (markup):
    Is that what you mean ?
     
    MyVodaFone, Jun 25, 2010 IP
  3. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #3
    The following will do this;

    SELECT firstname, lastname from name GROUP by firstname,lastname;
    Code (markup):
    If you want to limit it on an area code, use something like this, wuith the appropriate area code;

     SELECT firstname, lastname from name WHERE area = '1' GROUP by firstname,lastname;
    Code (markup):
    If you want to know how many people have that name in the area;

    SELECT firstname, lastname, count(*) as total from name WHERE area = '1' GROUP by firstname,lastname;
    Code (markup):
     
    lukeg32, Jun 25, 2010 IP
  4. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #4
    QUESTION for @Lukeg32 I think he wants unique name combinations, wouldn't your query's just out-put them all ?
     
    MyVodaFone, Jun 25, 2010 IP
  5. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #5
    Nay, it will group the (like) fields together.

    Consider this structure;

    firstname	|	lastname	|	area
    bob		|	james		|	1
    harry		|	james		|	2
    bob		|	james		|	1
    harry		|	bert		|	1
    Code (markup):
    Running this query
    SELECT firstname, lastname, count(*) as total from name WHERE area = '1' GROUP by firstname,lastname;
    Code (markup):
    Will return;

    firstname	|	lastname	|	total
    bob		|	james		|	2
    harry		|	bert		|	1
    Code (markup):
    As you can see - the names are unique as they have been grouped together. I have just seen your post, which is another way of doing it (DISTINCT); it depends if he cares about who'd in the area :)
     
    lukeg32, Jun 25, 2010 IP
  6. pmf123

    pmf123 Notable Member

    Messages:
    1,449
    Likes Received:
    81
    Best Answers:
    0
    Trophy Points:
    215
    #6
    yeah in this case, i just want to create a list of unique names, so the first function is good for me.

    Much appreciate everyone's input!
     
    pmf123, Jun 25, 2010 IP