设计的问题,要用很多技术去实现没有设计的功能,要费不可想象的劲。用于自省
由于设计需要,需要查询不重复的记录值,同类问题,想必大家都遇到过,于是乎马上GOOGLE一下,发现此类问题还挺多,解决方案也不少,仔细看看。
例如有如下表结构和值
table
fid name sex
1 a 男
2 b 男
3 c 女
4 d 女
5 a 男
6 b 男
方案一:distinct
select distinct name from table
得到结果:
name
a
b
c
d
实现效果,那如果要同时打开其它记录呢?再试试
select distinct name,id from table
测试没什么效果,查下得知,这样实际是要name和id字段都重复才被筛选。继续查找可得如下方法:
方案二:group by
select *, count(distinct name) from table group by name
Oracle下测试失败,据说MYSQL下通过,不管,继续思考....
翻翻书,试试
select min(fid),name,sex from table group by name
成功,现实如下结果:
fid name sex
1 a 男
2 b 男
3 c 女
4 d 女
继续思考,如果要打开所有记录,不指定字段用(*),貌似这方法就不行了!
select * from table where fid in(Select min(fid) FROM table group by name)
测试成功
fid name sex
1 a 男
2 b 男
3 c 女
4 d 女
方案三:
本来已经完了,突然想起前几天在网上查了查询数据中所有某字段不重复的记录
select * from table where name in(select name from table group by name having count(name)=2)
得到如下结果:
fid name sex
1 a 男
2 b 男
5 a 男
6 b 男
以此类推:
select * from table where name in(select name from table group by name having count(name)=1)
按道理说没问题,大家试试~~
再多的字段都全部现实。哎,原来如此简单!回顾网上方法distinct,Inner Join等等,麻烦,而且有很大局限性.
总结如下:
select distinct name from table打开不重复记录的单个字段
select * from table where fid in(Select min(fid) FROM table group by name)打开不重复记录的所有字段值
select * from table where name in(select name from table group by name having count(name)=1)打开不重复任意次数的所有记录
select * from HelpAnswer where HelpId in(select HelpId from HelpAnswer group by HelpId having count(HelpId)=1)
select HelpId from (
select distinct HelpId, Row_Number() Over(order by Creattime desc) As rownum, Creattime from (select distinct HelpId,Creattime from HelpAnswer)as temp) as d
where rownum between 1 And 10 order by Creattime desc
select HelpId, Row_Number() Over(order by Creattime desc) As rownum, Creattime from
(select HelpId,Creattime from HelpAnswer
where HelpId In (select distinct HelpId from HelpAnswer)
) as temp