需要帮助才能更正MySQL查询结果

时间:2014-09-28 21:47:15

标签: mysql sql

我正在处理一个应用程序,我有事件表。事件有类型。应用程序支持三种类型的事件。

  1. set_date(特定日期的事件)
  2. 天(在工作日重复的事件)
  3. 每月(一个月中任何一天的活动)
  4. 现在我有一个查询,我正在检查事件是否属于这些类型中的任何一种,并根据类型I传递值以与存储的值进行比较。以下是查询

    SELECT *, CASE alarm_type WHEN 'set_date' THEN FIND_IN_SET('2014-09-25',event_alarm_date)>0 WHEN 'days' THEN FIND_IN_SET('Mon',alarm_days)>0 WHEN 'monthly' THEN FIND_IN_SET('2',monthly_alarm_days)>0 END FROM events ev ORDER BY start_time

    `CREATE TABLE IF NOT EXISTS `events` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `event_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
      `start_time` time NOT NULL,
      `end_time` time NOT NULL,
      `is_repeated` tinyint(4) NOT NULL DEFAULT '0',
      `alarm_type` enum('set_date','days','monthly') COLLATE utf8_unicode_ci NOT NULL,
      `event_alarm_date` date DEFAULT NULL,
      `alarm_days` set('Sat','Sun','Mon','Tue','Wed','Thu','Fri') COLLATE utf8_unicode_ci DEFAULT NULL,
      `monthly_alarm_days` set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31') COLLATE utf8_unicode_ci DEFAULT NULL,
      `alarm_audio` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
      `created_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `count_down_time` tinyint(4) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
    
    --
    -- Dumping data for table `events`
    --
    
    INSERT INTO `events` (`id`, `event_name`, `start_time`, `end_time`, `is_repeated`, `alarm_type`, `event_alarm_date`, `alarm_days`, `monthly_alarm_days`, `alarm_audio`, `created_on`, `count_down_time`) VALUES
    (1, 'Lunch Break', '10:30:45', '11:30:45', 1, 'days', NULL, 'Mon,Wed', NULL, '1411587500.mp3', '0000-00-00 00:00:00', 0),
    (2, 'Openning Ceremony', '10:30:45', '11:30:45', 1, 'monthly', NULL, NULL, '2,3,4', '1411587568.mp3', '0000-00-00 00:00:00', 0),
    (3, 'Inspection', '10:30:45', '12:45:30', 0, 'set_date', '2014-09-26', NULL, NULL, '1411587695.mp3', '0000-00-00 00:00:00', 0),
    (5, 'Test2', '10:30:45', '11:30:45', 1, 'monthly', NULL, NULL, '3,4,5', '1411595801.mp3', '2014-09-24 21:56:41', 0),
    (6, 'Test3', '22:20:30', '23:25:30', 1, 'days', NULL, 'Sun,Mon', NULL, '1411597086.mp3', '2014-09-24 22:18:06', 0);`
    

    此查询应该有三行,但它会获取表中存在的所有五行。我已经过了2014-09-25的日期,这个日期在任何一行中都没有,但它会在2014-09-26之前排成一行。类似地,我已经为每月类型传递了2,并且只有一行有2个条目,但它获得了没有条目2的行。请帮助更正此查询。如果还有其他更好的解决方案,也欢迎。

1 个答案:

答案 0 :(得分:1)

也许你在这样的事情之后......

 SELECT *
   FROM events ev 

  WHERE CASE alarm_type WHEN 'set_date' THEN FIND_IN_SET('2014-09-25',event_alarm_date)>0 
                        WHEN 'days' THEN FIND_IN_SET('Mon',alarm_days) > 0 
                        WHEN 'monthly' THEN FIND_IN_SET('2',monthly_alarm_days) > 0 
        END = 1
  ORDER 
     BY start_time;