2

这是我的 MS Sql 表。表: http ://snag.gy/L6ag1.jpg

SELECT 
    * 
FROM Table1 
WHERE   
    Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate 
    or '3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        )

上面的查询返回表的所有 6 行,而下面的查询返回 0 行。

SELECT 
    * 
FROM Teacher 
WHERE   
    Class = '12' 
    AND Section = 'B' 
    and '12:00 PM'  between [StartTime] and endtime 
    and '1:00 PM' between [StartTime] and endtime 
    or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)

我期待顶部的查询返回 0 行,因为我使用了 AND 操作数,所以即使日期比较返回行,组合查询也不应该返回任何内容,因为时间比较返回 false。

创建表的脚本:

INSERT INTO [SLIITComDB].[dbo].[Teacher]
           ([TeacherId]
           ,[TeacherName]
           ,[Class]
           ,[Section]
           ,[SubjectId]
           ,[Date]
           ,[ToDate]
           ,[Day]
           ,[StartTime]
           ,[EndTIme]
           ,[Absent])
     VALUES
           (<TeacherId, int,>
           ,<TeacherName, varchar(50),>
           ,<Class, varchar(50),>
           ,<Section, varchar(50),>
           ,<SubjectId, varchar(50),>
           ,<Date, date,>
           ,<ToDate, date,>
           ,<Day, varchar(50),>
           ,<StartTime, time(7),>
           ,<EndTIme, time(7),>
           ,<Absent, varchar,>)
GO
4

2 回答 2

3

在 SQL 中,AND运算符优先于OR运算符。

因此,在您的第一个查询中,条件如下所示:

WHERE   
  ( Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate
   ) OR (
    '3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        ))

结果是TRUE顶部或底部(由 分隔OR)中的任何一个为TRUE.

第二个查询中的条件也如下所示:

WHERE   
  ( Class = '12'
    AND Section = 'B' 
    and '12:00 PM'  between [StartTime] and endtime 
    and '1:00 PM' between [StartTime] and endtime
   )
    or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)

即使时间比较都是FALSE因为您的前两个日期比较可以是,您的第一个查询也可以返回结果TRUE

于 2013-03-04T12:21:05.123 回答
1

实际上是您的 OR 导致了这种情况:

根据您的数据,或之前的第一部分是正确的。所以这些将被退回。添加括号以澄清事情。

真的:

 Class = '12' 
    AND Section = 'B' 
    AND '3/4/2013' BETWEEN DATE AND TODATE 
    and '3/14/2013' between Date and ToDate 

 OR

错误的:

'3/4/2013' < Date and '3/14/2013' > ToDate 
    AND (
            '12:00 PM'  between [StartTime] and endtime 
            and '1:00 PM' between [StartTime] and endtime 
            or ('12:00 PM' < StartTime and '1:00 PM' > EndTIme)
        )

试试这个简化:

select * 
from Table1 
where 1 = 1
or 2 = 2
and 1 = 3
于 2013-03-04T12:22:10.877 回答