SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
当前回答
SELECT *
FROM tblname
GROUP BY duplicate_values
ORDER BY ex.VISITED_ON DESC
LIMIT 0 , 30
在ORDER BY我刚刚把例子放在这里,你也可以在这里添加ID字段
其他回答
SELECT * from table where field in (SELECT distinct field from table)
好问题@aryaxt——你可以看出这是一个好问题,因为你5年前问过这个问题,而我今天在试图找到答案时偶然发现了它!
我只是试图编辑接受的答案,以包括这一点,但如果我的编辑没有使它:
如果你的表不是那么大,并且假设你的主键是一个自动递增的整数,你可以这样做:
SELECT
table.*
FROM table
--be able to take out dupes later
LEFT JOIN (
SELECT field, MAX(id) as id
FROM table
GROUP BY field
) as noDupes on noDupes.id = table.id
WHERE
//this will result in only the last instance being seen
noDupes.id is not NULL
您正在寻找一个由:
select *
from table
group by field1
偶尔也可以用不同的on语句来写:
select distinct on field1 *
from table
然而,在大多数平台上,上述两种方法都不能工作,因为其他列上的行为未指定。(第一种方法适用于MySQL,如果你使用的是MySQL的话。)
您可以获取不同的字段,并坚持每次选择任意一行。
在一些平台上(例如PostgreSQL, Oracle, T-SQL),这可以直接使用窗口函数完成:
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)上,您需要编写子查询,使您将整个表与其本身连接起来(示例),所以不推荐。
对于SQL Server,您可以使用dense_rank和其他窗口函数来获取指定列上具有重复值的所有行和列。这里有一个例子……
with t as (
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r1' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r2' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r3' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r4' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r5' union all
select col1 = 'a', col2 = 'a', col3 = 'a', other = 'r6'
), tdr as (
select
*,
total_dr_rows = count(*) over(partition by dr)
from (
select
*,
dr = dense_rank() over(order by col1, col2, col3),
dr_rn = row_number() over(partition by col1, col2, col3 order by other)
from
t
) x
)
select * from tdr where total_dr_rows > 1
这是对col1、col2和col3的每个不同组合进行行计数。
SELECT *
FROM tblname
GROUP BY duplicate_values
ORDER BY ex.VISITED_ON DESC
LIMIT 0 , 30
在ORDER BY我刚刚把例子放在这里,你也可以在这里添加ID字段