MySQL Query - 如何根据范围值选择行

时间:2013-08-05 17:48:55

标签: php mysql

对此问题有点疑问。有没有办法检查一个值是否在mysql查询结果中提供的范围内。

如何在没有先查询,将其分解为部分并使用BETWEEN的情况下查看邮政编码85012是否在ZipCodes字段内?

+---------+-------------+--------------------+------------+-------------+
| StyleID | HistStyleID | AutobuilderStyleID | FilterRule | ZipCodes    |
+---------+-------------+--------------------+------------+-------------+
|  355755 |  2013490103 | w2013k49m1t3       | includes   | 27000-36999 |
+---------+-------------+--------------------+------------+-------------+

:: UPDATE ::

此表还可以包含以下各种范围..

+---------+-------------+--------------------+------------+-------------------------------------+
| StyleID | HistStyleID | AutobuilderStyleID | FilterRule | ZipCodes                            |
+---------+-------------+--------------------+------------+-------------------------------------+
|  332492 |  2012493107 | w2012k49m31t7      | excludes   | 38600-39799,70000-71499,71600-79999 |
+---------+-------------+--------------------+------------+-------------------------------------+

1 个答案:

答案 0 :(得分:1)

与评论中建议的一样,您应该重新设计数据库:

CREATE TABLE Styles (
     StyleID INT PRIMARY KEY,
     HistStyleID INT, 
     AutobuilderStyleID VARCHAR(40),
     FilterRule VARCHAR(40)
)


CREATE TABLE ZipCodes (
     StyleID INT,
     RangeBegin INT,
     RangeEnd INT,

     FOREIGN KEY StyleID REFERENCES Styles(StyleID)
)

然后你可以进行如下查询:

SELECT DISTINCT StyleID FROM ZipCodes WHERE RangeBegin >= 85012 AND RangeEnd <= 85012