SQL/mysql-选择不重复/唯一,但返回所有列? [英] SQL/mysql - Select distinct/UNIQUE but return all columns?
问题描述
SELECT DISTINCT field1, field2, field3, ...... FROM table
我正在尝试完成以下sql语句,但我希望它返回所有列,这可能吗?像这样:
I am trying to accomplish the following sql statement but I want it to return all columns is this possible? Something like:
SELECT DISTINCT field1, * from table
推荐答案
您正在寻找一个分组依据:
You're looking for a group by:
select *
from table
group by field1
有时可以用一个不同的on语句来写:
Which can occasionally be written with a distinct on statement:
select distinct on field1 *
from table
但是,在大多数平台上,以上两种方法都不起作用,因为未指定其他列上的行为. (如果您正在使用的话,第一个可以在MySQL中使用.)
On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)
您可以获取不同的字段,并坚持每次选择一个任意行.
You could fetch the distinct fields and stick to picking a single arbitrary row each time.
在某些平台(例如PostgreSQL,Oracle,T-SQL)上,可以直接使用窗口函数来完成此操作:
On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:
select *
from (
select *,
row_number() over (partition by field1 order by field2) as row_number
from table
) as rows
where row_number = 1
在其他数据库(MySQL,SQLite)上,您需要编写子查询,以使您将整个表与自身连接(
On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.
这篇关于SQL/mysql-选择不重复/唯一,但返回所有列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!