Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select * with distinct id

Tags:

php

mysql

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!

like image 621
NotJay Avatar asked Aug 22 '12 14:08

NotJay


People also ask

How can I find unique table ID?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

How do I select unique records in MySQL?

You can use the DISTINCT command along with the SELECT statement to find out unique records available in a table. mysql> SELECT DISTINCT last_name, first_name -> FROM person_tbl -> ORDER BY last_name; An alternative to the DISTINCT command is to add a GROUP BY clause that names the columns you are selecting.

What is select * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

How do I find non duplicate records in MySQL?

The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.


1 Answers

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

like image 75
mellamokb Avatar answered Sep 24 '22 16:09

mellamokb