select distinct qstId,writeDate,infoId,(select realName from dbo.users where id = t.person )person,
(select productCategoryName from dbo.productCategory 
where productCategoryId in 
(select categoryId  
from dbo.product 
where productId  in (select t2.productId from dbo.quesProductRelation t2 where t2.quesId = t.qstId)
)) categoryId, 
((select productName from dbo.product 
where productId in
(select t1.productId from dbo.quesProductRelation t1 where t1.quesId = t. qstId))) productId,version, 
(select statusName from dbo.productStatus where statusId=t.productStatus)productStatus, 
(select bigName from dbo.bigDetail where bigId=t.questionBigCategory) questionBigCategory, 
(select smallName from dbo.smallDetail where smallId=t.questionSmallCategory) questionSmallCategory,questionDesc,result,reason,deal, 
(select descript from dbo.importDetail where importId=t.import)import,proce,dealer,measure,dealDate, 
(select descText from dbo.isCloseDetail  where isCloseId=t.isClose)isClose,re 
 from dbo.question_data t ,  dbo.productCategory t2,dbo.product t3,dbo.quesProductRelation t4
--where t.qstId = t4.quesId and t4.productId = 9 --根据选择产品查询
where t.qstId = t4.quesId and t4.productId = t3.productId and t3.categoryId = 2--按照产品类别或科室查询
order by qstId desc这个是个查询语句,现在主要问题,有很多个条件,作为where 后面的字句,条件可选可不选。涉及到问题表 question_data ,产品表 包括productId ,[productName],[categoryId]
而类别表是 [productCategoryId],[productCategoryName]
还有一个是问题产品关联表  quesProductRelation 包括[id],[quesId],[productId] 字段假如我在条件选择中,选择 了 按照类别查询。不知where 后面怎么写。还有麻烦给优化下。感觉特别慢

解决方案 »

  1.   

    把in改成exists 可以优化一部分效率
      

  2.   

    把子句创建临时表来用,这样效率会比较高,如果你要嵌套,把in替换成exists
      

  3.   

    用left join  和inner join 写吧 这sql语句几乎木有可读性
      

  4.   

    你可以将SQL写成字符串形式,这样就可以自由拼凑SQL语句了。
    然后用命令执行。
    declare @sql varchar(400)
      set @sql = 
        'update t_abc'+
        'set olstates=''L1000'',updater='''+@useId+''',updatedate=getdate(),confirmman='''+@useId+''' '+
            ',isConfirm=''1'' , confirmDate=getdate()'+
        ' where olno IN ( '+@olno +' ) and olstates in (''L0002'',''L0003'',''L0004'') '
    exec(@sql)