开发者

How to get distinct record from mysql table?

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 fetche开发者_如何学God because it has a zip code which is already in record No. 1


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;


TRY

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

OR

  SELECT * FROM student GROUP BY zip;


Altough in MySQL you can get away with:

SELECT *
FROM student
GROUP BY zip 

I would choose:

SELECT * 
FROM student t
  JOIN 
    ( SELECT MIN(id) AS minid
      FROM student
      GROUP BY zip
    ) AS grp
    ON grp.minid = t.id


Since presumably the other columns are of some interest....

 SELECT y.*
 FROM yourTable y,
 (SELECT MIN(y2.id)
  FROM yourTable y2
  GROUP BY y2.zip) ilv
 WHERE ilv.id=y.id;

(or you could use the max-concat trick)

update

Oracle have now removed the max concat trick from the linked page - but it is described elsewhere on the internet


Try Using

Select Distinct(zip),id,name group by zip;


Is there any problem if I use as this below?

select distinct zip,name,id from student;


select id, name, distinct(zip) from student;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜