How to override NULL value from aggregate query using MySQLdb module in 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.
Any recommendations on a simple way to do this? I figure this is an easy one, but I'm new to python s开发者_运维知识库o 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]
Thanks in advance!
Edit: "print min_date" outputs "None" if the value is null. I want to override it with a default value, such as "2010-01-01".
I could do this in the MySQL using a sub-query, but would prefer to do it in python.
Why do you say you need a subquery? You can just use COALESCE:
"select COALESCE(max(date_val), 'your_default_value_here') from my_table;"
Try this:
min_date = cur.fetchone()[0]
min_date = min_date if min_date is not None else default_value
精彩评论