2

I have a column that has month and years as columns.. I need to select a range out of the columns.. they don't seem to work with 2 ranges.

Table

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 statement:

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

This does not seem to work.

Do I have to convert these into date formats and use between?

4 Answers 4

6

What you are doing is something similar to "trying to go left and right at the same time".

Lets break the WHERE clause.

You are telling MySQL to get rows with

  1. Year = 2012 AND Year = 2013

  2. Month >= 10 AND Month <= 2

This will never be true.

Your WHERE clause should look like -

WHERE AccountId = 1 
and ((`Month` >= 10 AND `Year` = 2012)
OR (`Month` <= 2 AND `Year` = 2013))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

enclose the condition around parenthesis and use OR

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

Comments

0

To achieve what you want use 'or' instead of 'and'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.