Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在一个字段中执行年数范围的MySQL查询_Mysql_Sql - Fatal编程技术网

如何在一个字段中执行年数范围的MySQL查询

如何在一个字段中执行年数范围的MySQL查询,mysql,sql,Mysql,Sql,我正在使用一个表,该表使用了我需要能够提供的一些数据的年份范围 按年份选择介于这些范围之间的记录 | id | Make | Model | Year | |----------------|------------|------------ | | 1 | Chevrolet | Camaro | 2008 | | 2 | Chevrolet | Camaro | 2009 - 2014 | | 3 | Dodge

我正在使用一个表,该表使用了我需要能够提供的一些数据的年份范围 按年份选择介于这些范围之间的记录

| id | Make      | Model      | Year        |
|----------------|------------|------------ |
| 1  | Chevrolet | Camaro     | 2008        |
| 2  | Chevrolet | Camaro     | 2009 - 2014 |
| 3  | Dodge     | Avenger    | 2010 - 2015 |
| 4  | Dodge     | Challenger | 2008 - 2016 |   
| 5  | Ford      | Escape     | 2013        |
| 6  | Ford      | Mustang    | 2004 - 2012 |
| 7  | Ford      | Mustang    | 2015        |
例如,我希望能够选择2012年的所有车辆


这应该返回:2、3、4和6,如下表所示。

可能是这样的: 当然,如果具有年份范围的所有列都在同一上下文中,则必须检查该表,否则这将不起作用

select *
from table
where (Year = '2012' and substring( Year, 6, 1) <> '-')
 or   (  substring(Year, 6, 1) = '-'
     and substring(Year, 1, 4) <= '2012')
     and substring(Year, 8, 4) >= '2012'))
使用“左”和“右”确定范围

SELECT *
FROM yourtable
WHERE (LEFT(Year,4) <= '2012' AND RIGHT(Year,4) >= '2012')
SQL Fiddle:

如果年份列保证总是有一年或两年,那么您可以这样做:

SELECT
    *
FROM
    `my_table`
WHERE
    CAST(LEFT(`Year`, 4) AS SIGNED) <= 2012
    AND CAST(RIGHT(`Year`, 4) AS SIGNED) >= 2012

这将捕捉到2012年或2000-2015年等的专栏

您可以使用左/右键获取开始和结束年份:


为此,我将首先尝试重新构造数据库,以便在最长年份和最短年份中有两个单独的字段。然而,有时我们会被其他人糟糕的设计决策所困扰。在这种情况下,使用静默转换的子字符串_索引非常有用:

select t.*
from t
where 2012 >= (year + 0) and -- does silent conversion on the first value in the field
      2012 <= (substring_index(year, ' - ', -1) + 0);
如果以字符串形式输入年份,则不需要静默转换:

select t.*
from t
where '2012' >= substring_index(year, ' - ', 1) and
      '2012' <= substring_index(year, ' - ', -1);

第一个条件不是有害的吗?你可能会接受一些奇怪的数据,比如a2012445。^,而你的第二种情况已经在2010-2012年、2012-2013年以及2012年发生。@JulienBlanchard绝对正确!它实际上也是多余的!
select t.*
from t
where 2012 >= (year + 0) and -- does silent conversion on the first value in the field
      2012 <= (substring_index(year, ' - ', -1) + 0);
select t.*
from t
where '2012' >= substring_index(year, ' - ', 1) and
      '2012' <= substring_index(year, ' - ', -1);
SELECT t.*
FROM   t WHERE  LEFT(Year,4) <= '2012' AND RIGHT(Year,4) >= '2012'