表名: mytable id code date note
1 001 2008/1 AAA
2 001 2008/2 AAB
3 002 2008/1 ABC
4 002 2008/6 ABV
5 003 2008/1 ABC
6 003 2008/3 ABC
要求查出每个code对应最大date对应的note值:
例如如下结果: 001 2008/2 AAB
002 2008/6 ABV
003 2008/3 ABC 请问怎么写sql性能比较好??
我写的是select a.code,a.date,a.note from mytable a,(select code,max(date) from mytable group by code ) b
where a.code=b.code and a.date=b.date 可是这样写效率比较低,请大家帮忙些个性能好点的。
1 001 2008/1 AAA
2 001 2008/2 AAB
3 002 2008/1 ABC
4 002 2008/6 ABV
5 003 2008/1 ABC
6 003 2008/3 ABC
要求查出每个code对应最大date对应的note值:
例如如下结果: 001 2008/2 AAB
002 2008/6 ABV
003 2008/3 ABC 请问怎么写sql性能比较好??
我写的是select a.code,a.date,a.note from mytable a,(select code,max(date) from mytable group by code ) b
where a.code=b.code and a.date=b.date 可是这样写效率比较低,请大家帮忙些个性能好点的。
然后试下面的看看:
select a.code,a.date,a.note from mytable a where not exists (select 1 from mytable b
where b.code=a.code and b.date>a.date);
这句sql为什么性能比较差。具体需求如下:
这句sql为什么性能比较差。具体需求如下:
SELECT code, MAX(date), note FROM mytable a GROUP BY code;
就是不知道这种写法的效率怎么样,或者干脆增加一个codedate字段,将code+date放进去,就变成:
Select id,code,date,note From `mytable` Where codedate In(Select Max(codedate) From `mytable` Group By code)
Select id,code,date,note From `mytable` Where codedate In(Select Max(codedate) From `mytable` Group By code)