如何从mysql表中获取不同的记录?

发布于 2024-11-09 06:02:01 字数 219 浏览 0 评论 0原文

我有一个像这样的表 student

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

我想获取所有记录,但邮政编码不应重复。因此,对于上述表记录,应获取第 1 号和第 2 号记录。不会提取 3 号记录,因为它的邮政编码已在 1 号记录中

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

风月客 2024-11-16 06:02:01
SELECT DISTINCT fieldName FROM tableName;

以下查询将仅选择不同的“zip”字段。

SELECT DISTINCT zip FROM student;

SELECT * FROM tableName GROUP BY fieldName;

以下查询将选择所有字段以及不同的 zip 字段。

SELECT * FROM student GROUP BY zip;
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;
岁月染过的梦 2024-11-16 06:02:01

尝试

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

  SELECT * FROM student GROUP BY zip;

TRY

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

OR

  SELECT * FROM student GROUP BY zip;
空城之時有危險 2024-11-16 06:02:01

尽管在 MySQL 中你可以逃脱:

SELECT *
FROM student
GROUP BY zip 

我会选择:

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

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
聆听风音 2024-11-16 06:02:01

因为想必其他列也有一些兴趣......

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

(或者您可以使用 最大连接技巧)

更新

Oracle 现在已从链接页面中删除了最大连接技巧 - 但它是 在其他地方描述 互联网

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

暮光沉寂 2024-11-16 06:02:01

尝试使用

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

Try Using

Select Distinct(zip),id,name group by zip;
左秋 2024-11-16 06:02:01

如果我像下面这样使用有什么问题吗?

select distinct zip,name,id from student;

Is there any problem if I use as this below?

select distinct zip,name,id from student;
疯了 2024-11-16 06:02:01
select id, name, distinct(zip) from student;
select id, name, distinct(zip) from student;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文