我正在开发一个在线考试系统,如果用户的分数在管理员设置的范围内,我想从数据库中获取数据。
范围是动态的,由管理员设置。
示例:
表字段值:
outcome_id | outcome_range
1 | 2,5
2 | 6,10
3 | 11,15用户:
如果用户得到3分,它将从表中得到数据行结果id 1,因为得分在2-5之间。
发布于 2016-03-28 03:40:56
你可以把范围分开
表
outcome_id | min_outcome | max_outcome
1 | 2 | 5
2 | 6 | 10
3 | 11 | 15查询
SELECT * FROM table_name WHERE min_outcome <= 3 AND max_outcome >= 3创建表
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);发布于 2016-03-28 03:39:46
第二个值(最大值)可能是多余的,如果
( a)范围是连续的,
( 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发布于 2016-03-28 03:54:11
你不需要改变你的桌子结构。
只需使用SUBSTRING_INDEX mysql函数来找到作为min和max值的值。
SELECT `outcome_id`, `outcome_range` FROM `test` HAVING SUBSTRING_INDEX(`outcome_range`, ',', 1) <= 3 AND SUBSTRING_INDEX(`outcome_range`, ',', -1) >= 3这个漂亮的东西也是用WHERE子句来完成的。同样的结果也出来了。
SELECT `outcome_id`, `outcome_range` FROM `test` WHERE SUBSTRING_INDEX(`outcome_range`, ',', 1) <= 3 AND SUBSTRING_INDEX(`outcome_range`, ',', -1) >= 3这里我使用3作为静态值。你可以使用动态的。这是一个用户输入。
输出: outcome_id outcome_range 1,2,5
https://stackoverflow.com/questions/36255519
复制相似问题