mysql选择大于少于多列的位置

时间:2013-01-24 14:20:21

标签: mysql

我有一个列有月份和年份作为列。我需要从列中选择一个范围..它们似乎不适用于2个范围。

CREATE TABLE `sampletable` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `AccountId` int(11) unsigned NOT NULL,
  `CampaignId` int(11) unsigned NOT NULL,
  `CampaignName` varchar(115) NOT NULL DEFAULT '',
  `Sent` int(11) unsigned NOT NULL,
  `Month` int(11) unsigned NOT NULL,
  `Year` int(11) unsigned NOT NULL,
  `LocationId` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `AccountId_idx` (`AccountId`),
  KEY `monthy_year_idx` (`Month`,`Year`),
  KEY `locationid_idx` (`LocationId`)
) ENGINE=MyISAM AUTO_INCREMENT=1584

选择声明:

SELECT * FROM sampletable
WHERE AccountId = 1 
and (`Month` >= 10 AND `Year` = 2012)
and (`Month` <= 2 AND `Year` = 2013)
ORDER BY Year asc, month asc

这似乎不起作用。

我是否必须将这些转换为日期格式并在两者之间使用?

4 个答案:

答案 0 :(得分:4)

你正在做的事情类似于“试图同时左右移动”。

让我们打破WHERE条款。

您告诉MySQL使用

获取行
  1. Year = 2012 AND Year = 2013

  2. Month >= 10 AND Month <= 2

  3. 这永远不会成真。

    您的WHERE子句应该是 -

    WHERE AccountId = 1 
    and ((`Month` >= 10 AND `Year` = 2012)
    OR (`Month` <= 2 AND `Year` = 2013))
    

答案 1 :(得分:1)

 and (     
  (`Month` >= 10 AND `Year` = 2012)
 or (`Month` <= 2 AND `Year` = 2013))

答案 2 :(得分:1)

将括号内的条件括起来并使用OR

SELECT ...
FROM ...
WHERE AccountId = 1  AND   
      ((`Month` >= 10 AND `Year` = 2012) OR  (`Month` <= 2 AND `Year` = 2013) )

答案 3 :(得分:0)

要实现你想要的'或'而不是'和'。