MySQL 如何从mysql表中获取不同的记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6109758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get distinct record from mysql table?
提问by Student
I have a table studentlike 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
我想获取所有记录,但不应重复邮政编码。因此,对于上述表记录,应获取记录号 1 和 2。将不会提取记录号 3,因为它的邮政编码已在记录号 1 中
回答by Mukesh Chapagain
SELECT DISTINCT fieldName FROM tableName;
The following query will only select distinct 'zip' field.
以下查询将仅选择不同的“zip”字段。
SELECT DISTINCT zip FROM student;
SELECT * FROM tableName GROUP BY fieldName;
The following query will select all fields along with distinct zip field.
以下查询将选择所有字段以及不同的 zip 字段。
SELECT * FROM student GROUP BY zip;
回答by diEcho
TRY
尝试
SELECT DISTINCT(zip),id,name FROM student;
OR
或者
SELECT * FROM student GROUP BY zip;
回答by ypercube??
Altough in MySQL you can get away with:
虽然在 MySQL 中你可以逃脱:
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
回答by symcbean
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)
(或者你可以使用max-concat 技巧)
update
更新
Oracle have now removed the max concat trick from the linked page - but it is describedelsewhere onthe internet
回答by Deepesh
Try Using
尝试使用
Select Distinct(zip),id,name group by zip;
回答by sushil bharwani
Is there any problem if I use as this below?
如果我像下面这样使用有什么问题吗?
select distinct zip,name,id from student;
回答by user3464213
select id, name, distinct(zip) from student;