mysql stuff函数,如何在MySQL中以逗号分隔的字段中获取最大值?

I have a MySQL table that has a field of comma separated values. How do I get the maximum value?

Example:

CREATE TABLE `test`.`scale` (`scale` VARCHAR(500));

INSERT INTO `test`.scale

VALUES

('1,5,0.3,0.8,1'),

('0.5,0.7,0.1,0.3'),

('7,0.5,0.7,4');

scale:

1,5,0.3,0.8,1

0.5,0.7,0.1,0.3

7,0.5,0.7,4

answer:

5

0.7

7

How do I select the max value in this string?

Unfortunately I can't change the way the previous person implemented the comma separated solution. I hope there is a MySQL function that can help me out, otherwise I’ll have to do some messy PHP stuff.

解决方案

I don't believe SQL has a function for splitting strings. Here's some code that claims to do it, but I haven't tested it.

The deeper reason for this is that SQL desperately wants you to store your data in normalized form. In this particular case, this means that every field should represent a single piece of data about the subject of the row.

Essentially you'd store scale and answer in two separate tables, which you could match with one another using an ID for the question each one belongs to. Scale would have one row per scale option, not one row per scale:

OPTIONS ANSWERS

question | scaleoption question | answer

---------|------------ ---------|-------

1 | 1.5 1 | 5

1 | .3 2 | .7

1 | .8 ...

1 | 1

2 | .5

2 | .7

...

You could then use the query select max(scaleoption) from options where question = 2 to get the maximum option for question 2. This format also lets you do things like find all questions where one of the options is 1, or get a count of how many options a particular question has. It looks more complicated but it's a flexible, extendible, portable way to do things.

If you want to use your current format, you'll have to return the entire string and break it up in some other programming language.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值