0

我对 MySQL 中的嵌套 CASE 有点问题。

rest_opening_hours 表如下:

rest_opening_hours (
  restid int,
  day_of_week int,
  hours_open time,
  hours_close time,
)

然后我正在尝试执行查询。WHEN DAYOFWEEK(NOW()) = 1 位的原因是我注意到,如果您尝试在周日(第 1 天)带走,它只会返回 1,这会导致问题。

SELECT h.hours_close
FROM restaurants s
INNER JOIN rest_opening_hours h
ON s.id = h.restid
WHERE 
CASE 
    WHEN h.hours_close > h.hours_open
    THEN h.day_of_week = DAYOFWEEK(NOW()) 
ELSE 
    CASE 
        WHEN DAYOFWEEK(NOW()) = 1
        THEN h.day_of_week = 7
    ELSE
        h.day_of_week = DAYOFWEEK(NOW() - 1) 
    END 
END 
AND s.id = '2'
LIMIT 0 , 30

以下是 rest_opening_hours 表中的一些数据:

INSERT INTO `rest_opening_hours` (`restid`, `day_of_week`, `hours_open`, `hours_close`) VALUES
(2, 1, '17:00:00', '23:00:00'),
(2, 7, '17:00:00', '06:00:00'),
(2, 6, '17:00:00', '00:00:00'),
(2, 5, '17:00:00', '01:00:00'),
(2, 4, '17:00:00', '02:00:00'),
(2, 3, '03:00:00', '23:00:00'),
(2, 2, '17:00:00', '04:00:00');

我唯一的问题是,我的查询返回多条记录,我真的不明白为什么。查询返回(在周日 - 第 1 天)周日(第 1 天)和周六(第 7 天)的结果,而不仅仅是我在查询中预期的第 7 天!?

我希望返回结果“06:00”,因为今天是星期日(第 1 天)并且按照逻辑,当 DAYOFWEEK(NOW()) = 1 时,我们选择 where h.days_of_week = 7(即昨天的营业时间),因为我们之前推断出 h.hours_close < h.hours_open。但是,我得到了两个结果:“06:00”和“23:00”,这对我来说毫无意义,就好像 MySQL 忽略了第二种情况,只返回两者!??!?!

任何人都可以对此有所了解,因为我已经花了很长时间在玩这个,但我似乎没有得到任何结果。

提前致谢!

瑞安

修改后的查询

SELECT h.hours_close
FROM restaurants s
INNER JOIN rest_opening_hours h ON s.id = h.restid
WHERE 
CASE 
    WHEN h.hours_close > h.hours_open
    THEN h.day_of_week = DAYOFWEEK( NOW( ) ) 
    ELSE h.day_of_week = DAYOFWEEK( DATE_SUB( NOW( ) , INTERVAL 1 DAY ) ) 
END 
AND s.id =  '2'

看来我的问题是我的查询选择了前一天(7)和相关日期(1),因为一个是 h.hours_close > h.hours_open,另一个是 h.hours_close < h.hours_open - 任何想法关于如何将其隔离为一个结果,也许是某种重组,以便我只查看前一天的结果,如果关闭时间小于打开时间(即第二天关闭)。

在伪代码中:

if (closingtime < openingtime) {
return closing time from yesterday
} else {
return closing time from today
}

它是如此简单 - 为什么它会给我带来这么多该死的问题!?!?!?

4

1 回答 1

0

上帝保佑伪代码。这就是我所需要的:) 这就是你想要的:

select * from t1
join (
  select restid, day_of_week,
    if(hours_close < hours_open,
      if(day_of_week = 1, 7, day_of_week - 1),
      day_of_week
    ) as NewDayOfWeek
  from t1
) as S
on s.restid = t1.restid and s.day_of_week = t1.day_of_week
于 2012-02-12T06:26:36.010 回答