现在有2张表
table1:                                           table2:
id int1 int2 date int3 int4 int5         id int6 int7 int8select id from table1 left join table2 on table1.id=table2.id 
where int1!=1 and int2=2 and year(now()) - year(date) > 20 ... and int6=3 ... limit 0, 10 where的条件有些可能有,有些可能没有,有些可能是范围条件
1.这样的查询该怎么优化呢?
2.根据出生日期查询年龄范围有没有其他比较好的写法?
3.这种查询能不能写个mysql的函数。让java程序直接调来获取查询结果?
4.上面的sql语句有没有什么地方还可以优化?
本人刚接触数据库,大学里学的也基本忘光了,请各位大虾指点下!

解决方案 »

  1.   

    索引优化,仅针对某类WHERE语句。如果仅对下面语句来说
    select id from table1 left join table2 on table1.id=table2.id 
    where int1!=1 and int2=2 and year(now()) - year(date) > 20  and int6=3 
    limit 0, 10 改语句为select id from table1 left join table2 on table1.id=table2.id 
    where int1!=1 and int2=2 and `date`<  MAKEDATE(year(now()),1)  and int6=3 
    limit 0, 10 
    然后创建索引create index xxxx1 on table2(id,int6);
    create index xxxx2 on table1(int2,date,int1,id);
    至于为何如此,几百字很难讲清楚,如果感兴趣,则建议浏览一下MYSQL官方手册中的第七章,优化
      

  2.   

    我看《高性能mysql》里说不是要按索引的顺序写where语句吗,还有中间不能跳,而且除了最后一个中间中间不能范围查询。否则索引无效
      

  3.   


    手册中有详细的解释,MYSQL如何选择索引。 WHERE后的顺序你就直接忽略吧。