2

我正在尝试根据以下某些条件从我的表中获取一些行:

SELECT * FROM MyTable WHERE Date BETWEEN 
CASE dayofweek(curdate())
when 1 then curdate() AND adddate(curdate(), interval 6 day)
when 2 then subdate(curdate(), interval 1 day) AND adddate(curdate(), interval 5 day)
when 3 then subdate(curdate(), interval 2 day) AND adddate(curdate(), interval 4 day)
when 4 then subdate(curdate(), interval 3 day) AND adddate(curdate(), interval 3 day)
when 5 then subdate(curdate(), interval 4 day) AND adddate(curdate(), interval 2 day)
when 6 then subdate(curdate(), interval 5 day) AND adddate(curdate(), interval 1 day)
when 7 then subdate(curdate(), interval 6 day) AND curdate()
END

但由于某种原因它不起作用。它给了我一个语法错误。我应该如何完成这样的事情?

4

2 回答 2

1

试试这个,

SELECT * 
FROM MyTable 
WHERE  1 = 
    CASE dayofweek(curdate())
        when 1 then Date BETWEEN curdate() AND adddate(curdate(), interval 6 day)
        when 2 then Date BETWEEN subdate(curdate(), interval 1 day) AND adddate(curdate(), interval 5 day)
        when 3 then Date BETWEEN subdate(curdate(), interval 2 day) AND adddate(curdate(), interval 4 day)
        when 4 then Date BETWEEN subdate(curdate(), interval 3 day) AND adddate(curdate(), interval 3 day)
        when 5 then Date BETWEEN subdate(curdate(), interval 4 day) AND adddate(curdate(), interval 2 day)
        when 6 then Date BETWEEN subdate(curdate(), interval 5 day) AND adddate(curdate(), interval 1 day)
        when 7 then Date BETWEEN subdate(curdate(), interval 6 day) AND curdate()
    END

在这种CASE()情况下,语句将只返回两个可能的值:10

于 2013-04-21T08:12:59.327 回答
0

CASE 返回一个,而不是表达式。您必须对 BETWEEN 的每一侧重复 CASE 语句:

SELECT * FROM MyTable
WHERE Date BETWEEN 
  CASE dayofweek(curdate())
    when 1 then curdate()
    when 2 then subdate(curdate(), interval 1 day)
    ... etc
  END
AND -- this is the "AND" for the BETWEEN values
  CASE dayofweek(curdate())
  when 1 then adddate(curdate(), interval 6 day)
  when 2 then adddate(curdate(), interval 5 day)
  ... etc
END
于 2013-04-21T08:12:08.450 回答