简体   繁体   English

SQL SELECT查询列中的多个值和范围

[英]SQL SELECT Query for Multiple Values and Ranges in Column

SQL SELECT query for multiple values and ranges in row data of a given column. SQL SELECT查询给定列的行数据中的多个值和范围。

Problem description: 问题描述:

Server: MySQL 服务器:MySQL
Database: Customer 数据库: Customer
Table: Lan 表: Lan
Column: Allowed VLAN (in the range 1-4096) 列: Allowed VLAN (范围为1-4096)

One row has data as below in the column Allowed VLAN : 一行在“ Allowed VLAN ”列中包含以下数据:
180,181,200,250-499,550-811,826-mismatched

I need a SELECT statement WHERE the column Allowed VLAN includes a given number for instance '600' . 我需要一个SELECT语句WHEREAllowed VLAN包括例如给定数'600' The given number '600' is even one of the comma separated value or included in any of the ranges "250-499","550-811" or it is just the starting number value of "826-mismatched" range. 给定的数字'600'甚至是逗号分隔值之一,或包含在范围“ 250-499”,“ 550-811”中的任何一个中,或者仅仅是“ 826不匹配”范围的起始数字值。

SELECT * WHERE `Allowed VLAN`='600' OR `Allowed VLAN` LIKE '%600%' OR (`Allowed VLAN` BETWEEN '1-1' AND '1-4096');

I could not figure it out how to deal with data ranges with WHERE Clause. 我无法弄清楚如何使用WHERE子句处理数据范围。 I have solved the problem with PHP code using explode() split functions etc., but I think there are some SQL SELECT solutions. 我已经使用explode()拆分函数等解决了PHP代码的问题,但是我认为有一些SQL SELECT解决方案。

I would be appreciated for any help. 我将不胜感激。

I would highly recommend normalizing your data. 我强烈建议规范化您的数据。 Storing a comma-separated list of items in a single row is generally never a good idea. 在单行中存储逗号分隔的项目列表通常不是一个好主意。

Assuming you can make such a change, then something like this should work for you (although you could consider storing your ranges in different columns to make it even easier): 假设您可以进行这样的更改,那么类似的事情应该对您有用(尽管您可以考虑将范围存储在不同的列中以使其更加容易):

create table lan (allowedvan varchar(100));

insert into lan values 
  ('180'),('181'),('200'),('250-499'),('550-811'),('826-mismatched');

select *
from lan
where allowedvan = '600'
  or 
    (instr(allowedvan,'-') > 0 and 
     '600' >= left(allowedvan,instr(allowedvan,'-')-1) and
     '600' <= right(allowedvan,length(allowedvan)-instr(allowedvan,'-')) 
      )

SQL Fiddle Demo SQL小提琴演示

This uses INSTR to determine if the value contains a range (a hyphen) and then uses LEFT and RIGHT to get the range. 这使用INSTR来确定该值是否包含范围(连字符),然后使用LEFTRIGHT来获取范围。 Do not use LIKE because that could return inaccurate results (600 is like 1600 for example). 不要使用LIKE因为那样可能会返回不正确的结果(例如600类似于1600)。

If you are unable to alter your database, then perhaps look into using a split function (several posts on it on SO) and then you can do something similar to the above method. 如果您无法更改数据库,则可以考虑使用split函数(SO上的几篇文章),然后可以执行与上述方法类似的操作。

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

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