一句SQL语句的优化。。。
需求如下:
企业表Table_Corp,留言表Table_Msg;企业IsMoney>1为会员,<=1为非会员;ID为传入产品ID号,现取企业表前100条记录,如果是会员,每条产品只能发一次留言,没有条数限制,如果是非会员企业,每条产品只能发一次留言,但一天只有一条数量的限制。
SELECT TOP 100 CorpName, ID FROM Table_Corp a WHERE Status <> 4 AND ((IsMoney>1 and ID not in(select CorpID from Table_Msg Where ProdID="&ID&")) or (IsMoney<2 and ID not in(SELECT CorpID FROM Table_Msg WHERE (ProdID="&ID&") or (datediff(d, getdate(), requesttime) = 0 AND CorpID=a.ID))))
用以上能实现功能,但经常会超时。。。数据库为sql2000,求高手能对这语句优化或别的SQL,谢谢。。。
------解决方案--------------------SELECT TOP 100 CorpName, ID
FROM Table_Corp tc
LEFT JOIN Table_Msg tm
on tc.ID=tm.ProdID
WHERE tc.[Status]<>4
AND((tc.IsMoney>1 AND tc.ID <> tm.CorpID)
or
(tc.IsMoney<2 AND tc.ID<>tm.CorpID OR (datediff(d, getdate()tm.requesttime) = 0
AND tc.ID=tm.CorpID)
))
------解决方案--------------------试试这个:
SELECT TOP 100 CorpName, ID FROM Table_Corp a WHERE a.Status <> 4 AND NOT EXISTS (
SELECT * FROM Table_Msg m WHERE m.CorpID=a.ID AND (m.ProdID=@ID OR (a.IsMoney<=1 AND DateDiff(d,GETDATE(),m.requesttime)=0)) )