"其中"条件不符合预期("或"问题)

时间:2016-05-08 13:55:30

标签: sql

我有问题要加入4个表

Model of my database

我想计算不同种类的预订数量(用户[mrbs_users.id],房间[mrbs_room.room_id],区域[mrbs_area.area_id])。

我执行此查询时(对于用户(id = 1))

SELECT count(*)
FROM mrbs_users JOIN mrbs_entry ON mrbs_users.name=mrbs_entry.create_by 
                JOIN mrbs_room ON mrbs_entry.room_id = mrbs_room.id 
                JOIN mrbs_area ON mrbs_room.area_id = mrbs_area.id
WHERE mrbs_entry.start_time BETWEEN "145811700" and "1463985000" 
      or 
      mrbs_entry.end_time BETWEEN "1458120600" and "1463992200" and mrbs_users.id = 1 

结果是每个用户的预订总数,而不仅仅是拥有id = 1的用户。

所以,如果有人能帮助我......提前致谢。

2 个答案:

答案 0 :(得分:2)

只要有多个条件,就在where子句中使用括号。您的where被解析为:

WHERE (mrbs_entry.start_time BETWEEN "145811700" and "1463985000" ) or
      (mrbs_entry.end_time BETWEEN "1458120600" and "1463992200" and
       mrbs_users.id = 1
      )

据推测,你打算:

WHERE (mrbs_entry.start_time BETWEEN 145811700 and 1463985000  or
       mrbs_entry.end_time BETWEEN 1458120600 and 1463992200
      ) and
      mrbs_users.id = 1

另外,我删除了字符串常量周围的引号。混合数据类型是不好的做法,在某些数据库中,类型之间的转换会降低查询效率。

答案 1 :(得分:0)

由于条件错误WHERE导致您遇到的问题 所以,应该是:

  WHERE (mrbs_entry.start_time BETWEEN 145811700 AND 1463985000 )
         OR
        (mrbs_entry.end_time BETWEEN 1458120600 AND 1463992200 AND mrbs_users.id = 1)  

此外,当您仅使用INNER JOINJOIN)时,最好避免WHERE子句,因为ON子句在WHERE之前执行}子句,所以标准会更快。
在这种情况下,您的查询应该是这样的:

SELECT COUNT(*)
FROM mrbs_users 
     JOIN mrbs_entry ON mrbs_users.name=mrbs_entry.create_by 
     JOIN mrbs_room ON mrbs_entry.room_id = mrbs_room.id 
          AND
          (mrbs_entry.start_time BETWEEN 145811700 AND 1463985000 
            OR ( mrbs_entry.end_time BETWEEN 1458120600 AND 1463992200 AND mrbs_users.id = 1)       
          )         
     JOIN mrbs_area ON mrbs_room.area_id = mrbs_area.id