我似乎无法找到这个看似简单的问题的答案。大多数解决方案都删除所有重复项,选择所有重复项,或选择除重复项之外的所有记录。如何选择所有行,在此示例中,“name”列值是唯一的,同时选择任何重复集的第一个记录并忽略同名的剩余重复项?我确实需要所选记录集中所有记录中所有列的所有值。
Given the set of records:
pk fk name secs note
1 100 cat 90 gray
2 111 dog 123 mix
3 233 fish 75 gold
4 334 dog 932 black
5 238 cow 90 stray
6 285 cat 90 stray
The returned set should be:
pk fk name secs note
1 100 cat 90 gray
2 111 dog 123 mix
3 233 fish 75 gold
5 238 cow 90 stray
-- SQL
drop table if exists foo;
create table foo (
pk int unsigned,
fk int unsigned,
name varchar(10),
secs int,
note varchar(10),
primary key (pk)
) engine=innodb default charset=utf8;
insert into foo
(pk, fk, name, secs, note)
values
(1, 100, 'cat', 90, 'gray'),
(2, 111, 'dog', 123, 'mix'),
(3, 233, 'fish', 75, 'gold'),
(4, 334, 'dog', 932, 'black'),
(5, 238, 'cow', 90, 'stray'),
(6, 285, 'cat', 90, 'stray');
答案 0 :(得分:0)
我认为你正在寻找这个:
select * from table group by name;
可以使用distinct关键字编写:
select distinct on name * from table;
答案 1 :(得分:0)
这是一个返回您要查找内容的查询:
SELECT
F.*
FROM
foo F
INNER JOIN
( SELECT
MIN(F2.pk) AS `pk`
,F2.name
FROM foo F2
GROUP BY F2.name
) T
ON T.pk = F.pk;
希望这会对你有所帮助。
答案 2 :(得分:0)
In SQL it will be
select pk, fk, name, secs, note
from (select row_number()
over(partition by name order by pk) as rn,*
from foo) as tbl
where rn=1