简体   繁体   English

MySQL:如何在MySQL中选择范围?

[英]MySQL: How to select range in mysql?

I'm developing an online examination system and I want to get a data from the database if the score of the user is in the range set by the admin. 我正在开发一个在线考试系统,如果用户的分数在管理员设置的范围内,我想从数据库中获取数据。

Range is dynamic and set by the admin. 范围是动态的,由管理员设置。

Example: 例:

TABLE FIELDS VALUES: 表字段值:

outcome_id | outcome_range
     1     | 2,5
     2     | 6,10
     3     | 11,15

USER: 用户:

If the user got 3 points it will get the data row outcome id 1 from the table because the score is in the range of 2-5. 如果用户获得3分,它将从表中获得数据行结果ID 1 ,因为得分在2-5范围内。

The second value (the max-points) might be superfluous if 如果第二个值(最大点数) 可能是多余的
a) the ranges are continuous and a)范围是连续的,并且
b) you will select exactly 1 (or 0) outcome id b)您将精确选择1(或0)个结果ID

CREATE TABLE outcomes (
  outcome_id int,
  outcome_min int,
  unique index(outcome_min)
)

INSERT INTO outcomes (outcome_id,outcome_min) VALUES
  (1,2),
  (2,6),
  (3,11)

SELECT outcome_id FROM outcomes WHERE outcome_min>=3 ORDER BY outcome_min ASC LIMIT 1

You can separate the range 您可以分开范围

Table

outcome_id | min_outcome | max_outcome
     1     | 2           | 5
     2     | 6           | 10
     3     | 11          | 15

Query 询问

SELECT * FROM table_name WHERE min_outcome <= 3 AND max_outcome >= 3

Create table 建立表格

CREATE TABLE IF NOT EXISTS `table_name` (
  `outcome_id` int(11) NOT NULL AUTO_INCREMENT,
  `min_outcome` int(10) NOT NULL,
  `max_outcome` int(10) NOT NULL,
  PRIMARY KEY (`outcome_id`)
) ;

INSERT INTO `table_name` (`outcome_id`, `min_outcome`, `max_outcome`) VALUES
(1, 2, 5),
(2, 6, 10),
(3, 11, 15);

You not need to change your table structure. 您无需更改表结构。

just use SUBSTRING_INDEX mysql function to find the values as min and max value. 只需使用SUBSTRING_INDEX mysql函数查找最小值和最大值。

SELECT `outcome_id`, `outcome_range` FROM `test` HAVING SUBSTRING_INDEX(`outcome_range`, ',', 1) <= 3 AND SUBSTRING_INDEX(`outcome_range`, ',', -1) >= 3

This Pretty thing also done by using the WHERE clause. 也可以通过使用WHERE子句来完成此Pretty任务。 The same result come out. 同样的结果出来了。

SELECT `outcome_id`, `outcome_range` FROM `test` WHERE SUBSTRING_INDEX(`outcome_range`, ',', 1) <= 3 AND SUBSTRING_INDEX(`outcome_range`, ',', -1) >= 3

Here i use 3 as static value. 在这里我使用3作为静态值。 you can use the dynamic one. 您可以使用动态的。 This is a user input. 这是用户输入。

Output: 输出:

 outcome_id outcome_range 1 2,5 

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

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