MySQL根据记录求和和相减?
我在 mysql 中有一条记录,其中包含如下内容:
+15,+23,-21,+23,-3
我想要做的就是在 SQL 查询中,这些值根据它们的符号进行添加和减去。
我知道 SUM()
,但是减法呢?基本上,我需要一些可以在一个查询中执行的东西,如下例所示:
SELECT SUM(result) AS 'total' FROM mytable WHERE year='2011' AND month='10';
I have a record in mysql which contains something like this:
+15,+23,-21,+23,-3
All I want to do is that in a SQL query these values get added and subtracted according to their signs.
I know of SUM()
, but what about the subtraction? Basically, I need something that can be executed in one query, like the following example:
SELECT SUM(result) AS 'total' FROM mytable WHERE year='2011' AND month='10';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的查询将正常工作。测试
结果为8。
Your query will work correctly. Tested on
Result is 8.
您在数据库中使用逗号分隔字段。
这是一个巨大的 NONO,(My)SQL 没有很好的能力来处理这个问题。
如果每行中的值不超过 5 个,您可以执行以下操作:
尴尬代码警告
我不能 100% 确定 MySQL 会满意“+”符号,如果不是,您会需要通过执行
REPLACE(IFNULL(SUBSTRING_INDEX(result,',',2),0),'+','')
来过滤掉它们,请参阅:
http://dev.mysql.com/doc /refman/5.0/en/string-functions.html#function_substring-index
http://dev.mysql.com/doc/refman /5.0/en/string-functions.html#function_replace
重构数据库
我建议您改掉 CSV 的习惯并标准化您的数据库。
将值放入不同的行(每行一个值),并将
月
和年
列合并为一列,并添加auto_increment整数主键
名为id
的列您的表格将类似于:
现在,您可以通过执行以下操作来添加特定月份的结果总和:
使用
Between ... and
构造而不是函数YEAR(mydate) 和MONTH(mydate)
将允许 MySQL 使用索引来选择值。你将一个列包装在一个函数中 MySQL 不能使用索引,这会大大减慢速度。
You are using a comma separated field in your database.
That's a huge NONO, (My)SQL is not very well equipped to deal with this.
If you have no more than 5 values in every row you can do something like:
Awkward code warning
I'm not 100% sure MySQL will be happy with the '+' signs, if not you'll need to filter them out by doing
REPLACE(IFNULL(SUBSTRING_INDEX(result,',',2),0),'+','')
See:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
Refactoring you database
I recommend that you kick the CSV habit and normalize your database.
Put the values into different rows (one value per row) and merge the
month
andyear
columns into one, and add aauto_increment integer primary key
column namedid
Your table will look something like:
Now you can add the sum of results in a particular month by doing:
Using the
between ... and
construct instead of the functionsYEAR(mydate) and MONTH(mydate)
will allow MySQL to use an index to select the values.You you wrap a column in a function MySQL cannot use an index slowing things down a lot.