简体   繁体   English

sql - 在特定列中选择具有不同值的行

[英]sql - select rows with a distinct value in a specific column

Let's assume that I have the following table:让我们假设我有下表:

   id     player_name     team
   
   1      Gladiator        A
   2      DarkLord         B
   3      Alligator        A
   4      MonaLisa         C
   5      SpongBob         C
   6      Mikasa           B

I want to select one player from each team , which means that all the selected rows must have a unique value in the 'team' column.我想从每个团队中选择一名球员,这意味着所有选定的行在'team'列中必须具有唯一值。 How can I accomplish this in MySQL?如何在 MySQL 中完成此操作?

In my example the selected rows should be:在我的示例中,选定的行应该是:

   id     player_name     team
   
   1      Gladiator        A
   2      DarkLord         B
   4      MonaLisa         C

This is one way to do it using a derived table so you select one id per team and join it to the original table.这是使用派生表执行此操作的一种方法,因此您可以为每个团队选择一个 ID 并将其加入原始表。

select t.id, t.player_name, t.team
from tablename t
join (select team, min(id) as minid from tablename group by team) x
on x.team = t.team and x.minid = t.id

One simple way would be to fetch using a group by criteria.一种简单的方法是使用 group by 标准来获取。 (Assuming your table name is TEAM_TABLE) (假设你的表名是 TEAM_TABLE)

SELECT * FROM TEAM_TABLE GROUP BY TEAM;

This would return the first record occurring for each value of the team column.这将返回为team列的每个值出现的第一条记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM