Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct record from mysql table?

Tags:

mysql

distinct

I have a table student like this

id | name | zip 
1  | abc  | 1234
2  | xyz  | 4321
3  | asd  | 1234

I want to get all records but zip code should not be repeated. So In case of above table records, record No 1 and 2 should be fetched. Record No. 3 will not be fetched because it has a zip code which is already in record No. 1

like image 586
Student Avatar asked May 24 '11 11:05

Student


People also ask

How can I get distinct values from a table?

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 can I get distinct count of a column in MySQL?

MySQL COUNT(DISTINCT) function returns a count of number rows with different non-NULL expr values. Where expr is a given expression. The following MySQL statement will count the unique 'pub_lang' and average of 'no_page' up to 2 decimal places for each group of 'cate_id'.


2 Answers

SELECT DISTINCT fieldName FROM tableName;

The following query will only select distinct 'zip' field.

SELECT DISTINCT zip FROM student;

SELECT * FROM tableName GROUP BY fieldName;

The following query will select all fields along with distinct zip field.

SELECT * FROM student GROUP BY zip;
like image 75
Mukesh Chapagain Avatar answered Sep 19 '22 04:09

Mukesh Chapagain


TRY

 SELECT DISTINCT(zip),id,name FROM student;

OR

  SELECT * FROM student GROUP BY zip;
like image 40
diEcho Avatar answered Sep 19 '22 04:09

diEcho