34

I am trying to select a row with a distinct id, yet return all the fields.

SELECT * DISTINCT(ID) FROM table WHERE ...

I ultimately need the ID, City, State and Zip. How can I get rows that are not duplicate ID's and return all fields into my mysql_fetch_array?

I have tried the following:

SELECT * DISTINCT(ID) FROM table WHERE ...

SELECT DISTINCT ID * FROM table WHERE ...

SELECT ID,City,State,Zip DISTINCT ID FROM ...

SELECT ID,City,State,Zip DISTINCT(ID) FROM ...

I was reading other questions here and none seem to help. Thanks in advance!

5
  • DISTINCT will simply return unique IDs from the table; what are you trying to do exactly? Aug 22, 2012 at 14:38
  • 1
    I need more than just the IDs... thanks though
    – NotJay
    Aug 22, 2012 at 14:38
  • 1
    So with same id, which record should be selected?
    – xdazz
    Aug 22, 2012 at 14:38
  • 5
    if there are multiple records of same ID having different addresses... which address would you then want? random?
    – poncha
    Aug 22, 2012 at 14:39
  • I wanted to select 4 rows with different ID's which I would use the City, State and Zip. I needed to make sure that duplicate ID's were ignored because I am sorting the data returned. As far as ID's that have different addresses, it shouldn't matter which address to show, I just don't want duplicates. Thanks for your help, problem averted.
    – NotJay
    Aug 22, 2012 at 14:51

1 Answer 1

51

Try using GROUP BY:

  select id, city, state, zip
    from mytable
group by id

Note that this will return an arbitrary address for each id if there are duplicates.

Demo: http://www.sqlfiddle.com/#!2/c0eba/1

5
  • would I add the group by before or after the WHERE?
    – NotJay
    Aug 22, 2012 at 14:42
  • 6
    @NotJay - group by goes after the where Aug 22, 2012 at 14:42
  • 12
    @NotJay: Let me just point out that this is an atypical use of GROUP BY. The main purpose is for aggregation, that is to find MIN, MAX, SUM or other summary value per group. For instance, you might use GROUP BY to combine results of sales data by month to generate monthly totals and averages. I'm exploiting the fact that mysql allows you to refer to columns not being grouped in a query, which is undefined behavior (disallowed) in most other database systems. Cheers!
    – mellamokb
    Aug 22, 2012 at 14:52
  • @mellamokb: good point, you should add it to the answer, rather than leaving it in a comment!
    – nico
    Aug 22, 2012 at 16:59
  • it always returns me all the fields, using the same query ... any idea how to do this?
    – jpganz18
    Oct 30, 2014 at 15:39

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.