MySQL: check if a value is contained in a range interval

自作多情 提交于 2019-12-10 17:43:49

问题


I was wondering if it is possible to check if a string value is contained in a column given that the column contains the start and end values.

For example: if the table has a column NR with the following rows:

400-500
45-76,23-25
12,14-19,21

I want to find the row which has the value 421 in it. So the answer should be the first row.

Is this possible in mysql?


回答1:


You should have two tables: one for columns, one for column ranges. With that, a simple query will retrieve what you need.

CREATE TABLE foo (
    foo_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (foo_id)
)
ENGINE=InnoDB;

CREATE TABLE foo_range (
    foo_id INT(10) UNSIGNED NOT NULL,
    column_from INT(10) UNSIGNED NOT NULL,
    column_to INT(10) UNSIGNED NOT NULL,
    INDEX foo_range_fk1 (foo_id),
    CONSTRAINT foo_range_fk1 FOREIGN KEY (foo_id) REFERENCES foo (foo_id)
)
ENGINE=InnoDB;

INSERT INTO foo(foo_id)
VALUES (1), (2), (3);

INSERT INTO foo_range(foo_id, column_from, column_to)
VALUES (1, 400, 500), (2, 45, 74), (2, 23, 25), (3, 12, 14), (3, 19, 21);

SELECT foo_id
FROM foo_range
WHERE 421 BETWEEN column_from AND column_to;

And, actually, the main table is not even necessary unless you want to store additional data :)

If you are stuck with the other DB design, you'll probably have to retrieve all rows and use your client side language to do the matching.




回答2:


I agree with the above comments. Add two columns to your table and update it using substring_index() function

update table
set lft_value = substring_index(value,'-',1),
rgt_value = substring_index(value,'-',-1) 

If everything works fine remove your original values. Now it will be very simple to find values within lower and upper limits.

edit. Keeping your table structure the query would become:

select * from table
where 421 between
substring_index(value,'-',1),
and substring_index(value,'-',-1) 

but I don't like this solution.



来源:https://stackoverflow.com/questions/6995595/mysql-check-if-a-value-is-contained-in-a-range-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!