表结构 table A
id title xx xx date identityid
select A.id from A where A.identityid is not null order by A.date由于identityid字段可能有null值,也可能有重复的值。空值我用了is not null;重复的值使用group by 会导致order by无效。如果使用 distionct A.identityid 返回的值就不是id了。
请问下,如果不用子查询,有什么好的办法吗?
id title xx xx date identityid
select A.id from A where A.identityid is not null order by A.date由于identityid字段可能有null值,也可能有重复的值。空值我用了is not null;重复的值使用group by 会导致order by无效。如果使用 distionct A.identityid 返回的值就不是id了。
请问下,如果不用子查询,有什么好的办法吗?
假设ID唯一
select A1.id from A a1 where A1.identityid is not null
and not exists(select 1 from a where a1.identityid=identityid and a1.id<>id)
order by A1.date
这样写 order by 就无效了
from A
where A.identityid is not null
group by A.id
order by A.date
select A.id ,min(A.date)
from A
where A.identityid is not null
group by A.id
order by 2
1 1 2011-01-02 00:00:00 test1
2 1 2011-01-01 00:00:00 test2
3 1 2011-01-21 00:00:00 test3
4 2 2011-01-01 00:00:00 test4
5 2 2011-02-01 00:00:00 test5
6 2 2011-01-01 00:00:00 test6
7 3 2011-01-11 00:00:00 test7
8 3 2011-01-08 00:00:00 test8
9 null 2011-01-01 00:00:00 test9
10 null 2011-01-01 00:00:00 test10
11 null 2011-01-01 00:00:00 test11我需要的结果是:
id 3
id 5
id 7
现在sql语句也写出来了:
select SUBSTRING_INDEX(group_concat(t.id order by t.credate desc),',',1) from test as t
where t.identityid is not null group by t.identityid
上面可以满足我上面的需求。但是在hibernate里不能执行。不知道还有没有其它的写法?
SELECT * FROM TTH A WHERE identityid is not null AND NOT EXISTS(SELECT 1 FROM TTH WHERE A.identityid=identityid AND A.credate<credate)
可以自己写一个
用子查询的话 10楼的很好了、
(select identityid,max(credate) as ma from tt where identityid is not null group by identityid ) b
on a.identityid=b.identityid and a.credate=ma
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。