【问题标题】:mysql select where greater than less than multiple columnsmysql选择大于小于多列的地方
【发布时间】:2013-01-24 14:20:21
【问题描述】:

我有一列包含月份和年份。我需要从这些列中选择一个范围。它们似乎不适用于 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

这似乎不起作用。

我必须将这些转换为日期格式并在它们之间使用吗?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你正在做的事情类似于“试图同时向左和向右走”。

    让我们打破WHERE 子句。

    你告诉MySQL

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

    2. Month &gt;= 10 AND Month &lt;= 2

    这永远不会是真的。

    你的WHERE 子句应该看起来像 -

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

    【讨论】:

      【解决方案2】:
       and (     
        (`Month` >= 10 AND `Year` = 2012)
       or (`Month` <= 2 AND `Year` = 2013))
      

      【讨论】:

        【解决方案3】:

        用括号括住条件并使用OR

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-11-19
            • 2013-07-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-29
            • 1970-01-01
            相关资源
            最近更新 更多