这是我用来重现问题的表定义:
create table test_sum_type
(
kind char(1) not null,
n tinyint not null
);
测试数据:
+------+---+
| kind | n |
+------+---+
| A | 1 |
| B | 1 |
| A | 2 |
+------+---+
使用 MySQLdb
查询:
In [32]: cur.execute("select kind, sum(n) from test_sum_type group by kind")
Out[32]: 2L
In [33]: cur.fetchall()
Out[33]: (('A', Decimal('3')), ('B', Decimal('1')))
In [34]: cur.execute("select kind, n from test_sum_type")
Out[34]: 3L
In [35]: cur.fetchall()
Out[35]: (('A', 1), ('B', 1), ('A', 2))
如您所见,当我使用 sum
时,结果列是 Decimal
。
我查看了 MySQLdb 的源代码,只有两种字段类型设置为默认转换为 Decimal
:DECIMAL
和 NEWDECIMAL
。
这可能是什么原因?有没有办法检查特定查询中使用的某些临时表的模式?
最佳答案
它是 MySql 中的设计。
GROUP BY (Aggregate) Functions
The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE). (Before MySQL 5.0.3, SUM() and AVG() return DOUBLE for all numeric arguments.)
如果你需要返回一个INT
然后CAST
它。
SELECT kind, CAST(SUM(n) AS SIGNED) n
FROM table1
GROUP BY kind
这是 SQLFiddle 演示
关于python - MySQLdb 为 `Decimal` 的 `sum` 返回 `INT`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006049/