DATE_SUB问题

时间:2011-06-04 08:24:50

标签: php mysql

我的代码:

$song = mysql_query("SELECT COUNT(*) FROM `".$this->prefix."playlist`  
          WHERE `time` > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 20 MICROSECOND) 
          AND `long` < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 20 MICROSECOND)");
if(mysql_result($song, 0, 0) == 0)
{
  return "כלום";
} else {
  $query = mysql_query("SELECT * FROM `".$this->prefix."playlist`  
          WHERE `time` > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 20 MICROSECOND) 
          AND `long` < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 20 MICROSECOND)");
  $song = mysql_fetch_assoc($query);

  return $song["song"];
}

它应该返回现在播放的歌曲。

MYDB:

1   till the worlds ends    2011-06-04 11:20:10 2011-06-04 11:21:10 zRafael

时间:

11:20

它返回:“כלום”而不是歌曲名称

这是我的表:

CREATE TABLE IF NOT EXISTS `playlist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `song` varchar(150) NOT NULL,
  `time` varchar(150) NOT NULL,
  `long` varchar(150) NOT NULL,
  `by` varchar(150) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `playlist`
--

INSERT INTO `playlist` (`id`, `song`, `time`, `long`, `by`) VALUES
(1, 'till the worlds ends', '2011-06-04 11:40:10', '10', 'zRafael');

1 个答案:

答案 0 :(得分:0)

我会重写这个以避免第二个查询,这应该可行

再次更新 - 您的日期字段为VARCHAR,而不是DATETIME,因此我之前的查询无效。

$rs = mysql_query("SELECT song FROM `".$this->prefix."playlist`  
   WHERE CAST(`time` AS DATETIME) >= NOW() 
   AND CAST(`long` AS DATETIME) < NOW()");
if (mysql_num_rows($rs) == 0)
  return "כלום";
else
  return mysql_result($rs, 0);

实际上你应该修复你的表定义。

ALTER TABLE `playlist` 
  MODIFY COLUMN `time` DATETIME NOT NULL
  , MODIFY COLUMN `long` DATETIME NOT NULL;

然后你不需要那些演员表,你的数据库查找会更快。