简体   繁体   English

mysql选择大于多于小于的列

[英]mysql select where greater than less than multiple columns

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. 我有一列以月和年为列的列。我需要从列中选择一个范围。它们似乎不适用于2个范围。

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? 我是否必须将它们转换为日期格式并在之间使用?

What you are doing is something similar to "trying to go left and right at the same time". 您正在执行的操作类似于“尝试同时左右移动”。

Lets break the WHERE clause. 让我们打破WHERE子句。

You are telling MySQL to get rows with 您正在告诉MySQL获取行

  1. Year = 2012 AND Year = 2013

  2. Month >= 10 AND Month <= 2

This will never be true. 这将永远是不正确的。

Your WHERE clause should look like - 您的WHERE子句应类似于-

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

enclose the condition around parenthesis and use OR 将条件括起来并使用OR

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

要实现您想要的目标,请使用“或”而不是“与”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM