在SQL查询中为2列选择Distinct

时间:2021-12-23 04:28:51

If I have a table such as

如果我有一张桌子如

1 bob
1 ray
1 bob
1 ray
2 joe
2 joe

And I want to select distinct based on the two columns so that I would get

我想根据两列选择不同的,以便我得到

1 bob
1 ray
2 joe

How can I word my query? Is the only way to concatenate the columns and wrap them around a distinct function operator?

我该如何说出我的查询?是连接列并将它们包装在一个独特的函数运算符周围的唯一方法吗?

2 个解决方案

#1


25  

select distinct id, name from [table]

or

要么

select id, name from [table] group by id, name

#2


5  

You can just do:

你可以这样做:

select distinct col1, col2 from your_table;

That's exactly what the distinct operator is for: removing duplicate result rows.

这正是独特运算符的用途:删除重复的结果行。

Keep in mind that distinct is usually a pretty expensive operation, since, after processing the query, the DB server might perform a sort operation in order to remove the duplicates.

请记住,distinct通常是一个相当昂贵的操作,因为在处理查询之后,DB服务器可能会执行排序操作以删除重复项。

#1


25  

select distinct id, name from [table]

or

要么

select id, name from [table] group by id, name

#2


5  

You can just do:

你可以这样做:

select distinct col1, col2 from your_table;

That's exactly what the distinct operator is for: removing duplicate result rows.

这正是独特运算符的用途:删除重复的结果行。

Keep in mind that distinct is usually a pretty expensive operation, since, after processing the query, the DB server might perform a sort operation in order to remove the duplicates.

请记住,distinct通常是一个相当昂贵的操作,因为在处理查询之后,DB服务器可能会执行排序操作以删除重复项。