表名: 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.   

    这种方法效率不算低啊。你的 code ,date 上是否已经创建了索引?
      

  2.   

    没有建的,有1万笔记录,大概的执行3秒多。就这sql今天被老大吊了,还没想出好办法。
      

  3.   

    先建一下(code ,date )索引再说
      

  4.   

    先建立(code,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);
      

  5.   

    请大家帮忙分析select a.code,a.date,a.note from mytable  a,(select code,max(date) from mytable group by code  ) b
    这句sql为什么性能比较差。具体需求如下:
      

  6.   

    请大家帮忙分析select a.code,a.date,a.note from mytable  a,(select code,max(date) from mytable group by code  ) b
    这句sql为什么性能比较差。具体需求如下:
      

  7.   

    建立(code,date)的复合索引 
      

  8.   

    MySQL允许这么写:
    SELECT code, MAX(date), note FROM mytable a GROUP BY code;
      

  9.   

    Select id,code,date,note From `mytable` Where concat(code,date) In(Select concat(code,Max(date)) From `mytable` Group By code)
    就是不知道这种写法的效率怎么样,或者干脆增加一个codedate字段,将code+date放进去,就变成:
    Select id,code,date,note From `mytable` Where codedate In(Select Max(codedate) From `mytable` Group By code)
      

  10.   

    Select id,code,date,note From `mytable` Where concat(code,date) In(Select concat(code,Max(date)) From `mytable` Group By code)就是不知道这种写法的效率怎么样,或者干脆增加一个codedate字段,将code+date放进去,就变成: 
    Select id,code,date,note From `mytable` Where codedate In(Select Max(codedate) From `mytable` Group By code)
      

  11.   

    SELECT code,max(date),note FROM mytable group by code;