我们的项目代码中有两条SQL查询语句:1. select *
          from datainput t
          where t.templateid =
                           (select max(templateid) from datainput d where t.unitid = d.unitid);
       2. select * from datainput t where t.templateid = (select max(templateid) from datainput);其中第1条语句是项目中别人写的,我的理解是将datainput表中templateid最大的记录数显示出来(templateid有重复), 但是在我的看来where t.unitid = d.unitid就是多余的所以如果我写的话,我肯定会写成第2条SQL语句的形式, 请问大家的是这两条SQL语句有区别吗,我的理解是否正确? 是否第1条SQL语句的自连接查询效率会更高?谢谢!

解决方案 »

  1.   

    两个sql是不同的,举例来说
    templateid    t.unitid 
    1                 1
    2                 2
    3                 1
    4                 2
    第一句的查询结果为
    3                 1
    4                 2
    第二个则为
    4                 2
      

  2.   


    这个类似group by 分组..你可以执行一下两条PUBS库的数据看看就知道了..
    1:  表示同一组内,最高的价格
       select * from titles t where t.price = (select max(price) from titles d where t.pub_id = d.pub_id)
    2:  表示不分类型,只要取最高的价格
    select * from titles t where t.price = (select max(price) from titles d )语句写 好了效率就高...
      

  3.   

    不单单是效率的问题,两条语句的结果有可能不一样第一条语句求的是unitid相等的最大值,第二条语句是无条件的最大值
      

  4.   

    那是不是可以这样理解:第1条语句是按照unitid分组 (group by unitid), 求出每一组中templateid最大的记录
    第2条语句没有分组,只是求出全部记录中的templateid最大的记录
      

  5.   

    再问一下:select * from datainput t 
             where t.templateid = 
                              (select max(templateid) from datainput d where t.unitid = d.unitid);和select * from datainput t 
             where t.templateid in (select max(templateid) from datainput group by unitid);这两条SQL语句所查询出来的结果是相同的吗 ?
      

  6.   

    我在pubs里面测试的数据是不一样的..你执行以下就知道了..
      

  7.   

    PUBS库是啥数据库啊,怎么测呢
      

  8.   


    晕倒掉...那你换系统库..
    select * from scott.emp e where e.sal = (select max(sal) from scott.emp m where e.deptno = m.deptno);
    select * from scott.emp e where e.sal = (select max(sal) from scott.emp m);这两句执行的结果页是不一样的..
    同一部门最高工资的.
    跟同一个公司的最高工资..这样明白了吧...⊙﹏⊙b汗..
      

  9.   

    select * from datainput t 
            where t.templateid = 
                              (select max(templateid) from datainput d where t.unitid = d.unitid); 和 select * from datainput t 
            where t.templateid in (select max(templateid) from datainput group by unitid); 这两条SQL语句所查询出来的结果是相同的吗 ?
      

  10.   


    结果肯定是不一样的..这条是多对多的
    select * from datainput t where t.templateid =  (select max(templateid) from datainput d where t.unitid = d.unitid); 
    这条是多对一的,跟你没写group by 的结果是一样的...
    select * from datainput t where t.templateid in (select max(templateid) from datainput group by unitid);  
      

  11.   

    查出的结果都不一样.
    第一个是只有当t.unitid = d.unitid时的最大值。
    第二条是所有信息的最大值。
    可以说完全是两个意思