条件无效的地方

时间:2016-01-25 08:24:45

标签: mysql where-clause

我有一个SQL查询。但是那里包含where条件,而OR在那里不起作用。

查询

SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status` 
FROM (`st_student`)
WHERE `st_status` =  1
OR `st_status` =  2
AND `ab_date` BETWEEN '08/01/2015' AND '08/31/2015'
OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015'
AND `aca_no` =  2
GROUP BY `st_student`.`st_id` 

这种情况不起作用:

OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015'

那有什么错误吗?

2 个答案:

答案 0 :(得分:0)

一个可能的错误涉及使用ANDOR运算符,因为AND优先于OR,并且您的查询可能以错误的方式解释。所以你应该使用括号,写下这样的东西:

SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status` 
FROM `st_student`
WHERE (`st_status` =  1 OR `st_status` =  2)
AND (`ab_date` BETWEEN '08/01/2015' AND '08/31/2015'
     OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015')
AND `aca_no` =  2
GROUP BY `st_student`.`st_id` 

答案 1 :(得分:0)

如果您的列声明为varchar数据类型,则需要使用str_to_date函数。除非您将Varchar转换为一个日期,否则无法将其作为日期进行比较。试试这个让我知道。祝你好运。

  SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status` 
  FROM `st_student`
  WHERE (`st_status` =  1 OR `st_status` =  2)
  AND STR_TO_DATE(`ab_date`,'%d/%m/%Y')
  BETWEEN
  STR_TO_DATE('01/08/2015','%d/%m/%Y') 
  AND 
  STR_TO_DATE('31/08/2015','%d/%m/%Y')
  OR 
  STR_TO_DATE(`as_date`,'%d/%m/%Y')
  BETWEEN
  STR_TO_DATE('01/08/2015','%d/%m/%Y') 
  AND 
  STR_TO_DATE('31/08/2015','%d/%m/%Y')
  AND `aca_no` =  2
  GROUP BY `st_student`.`st_id`