如何在python中使用MySQLdb模块从聚合查询中覆盖NULL值? [英] How to override NULL value from aggregate query using MySQLdb module in python?

查看:80
本文介绍了如何在python中使用MySQLdb模块从聚合查询中覆盖NULL值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MySQLdb模块从python中的MySQL数据库表中选择最大日期值.如果结果返回为null,我想用默认值覆盖它.我可以在MySQL中使用子查询来做到这一点,但宁愿在python中做到这一点.

I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but would prefer to do it in python.

是否有关于此操作的简单建议?我认为这很简单,但是我是python的新手,所以我认为值得一问.

Any recommendations on a simple way to do this? I figure this is an easy one, but I'm new to python so I thought it was worth asking.

到目前为止,这是我的代码:

Here's my code so far:

db=MySQLdb.connect(...)
cur = db.cursor()
cur.execute("select max(date_val) from my_table;")
min_date = cur.fetchone()[0]

提前谢谢!

修改: 如果值为null,则"print min_date"输出"None".我想使用默认值覆盖它,例如"2010-01-01".

"print min_date" outputs "None" if the value is null. I want to override it with a default value, such as "2010-01-01".

推荐答案

尝试一下:

min_date = cur.fetchone()[0]
min_date = min_date if min_date is not None else default_value

这篇关于如何在python中使用MySQLdb模块从聚合查询中覆盖NULL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆