MySQL 查询某个字段不重复的所有记录
程序员文章站
2023-12-10 08:14:52
假设现在有如下n条记录 表明叫book id author title 1 aaa aaa 2 bbb bbb 3 ccc ccc 4 ddd ddd 5 eee aaa...
假设现在有如下n条记录 表明叫book
id author title
1 aaa aaa
2 bbb bbb
3 ccc ccc
4 ddd ddd
5 eee aaa
现在想从这5条记录中查询所有title不重复的记录
select distinct title,author from book这样是不可以的 因为distinct只能作用于一个字段
想请教应该怎么写
答案:
select a.* from book a right join (
select max(id) id from book group by title) b on b.id = a.id
where a.id is not null
如果选第一条符合的记录,那么用min(id)就行了
select a.* from book a right join (
select min(id) id from book group by title) b on b.id = a.id
where a.id is not null
id author title
1 aaa aaa
2 bbb bbb
3 ccc ccc
4 ddd ddd
5 eee aaa
现在想从这5条记录中查询所有title不重复的记录
select distinct title,author from book这样是不可以的 因为distinct只能作用于一个字段
想请教应该怎么写
答案:
复制代码 代码如下:
select a.* from book a right join (
select max(id) id from book group by title) b on b.id = a.id
where a.id is not null
如果选第一条符合的记录,那么用min(id)就行了
复制代码 代码如下:
select a.* from book a right join (
select min(id) id from book group by title) b on b.id = a.id
where a.id is not null