用 Python 编写此 SQL 的更好方法
无论如何我可以减少我的论点的重复吗?例如,时间模式重复 4 次,并且很难跟踪大型查询。
sql = ( "SELECT IFNULL(b.inviters/COUNT(DISTINCT c.id),0), "
" FROM_UNIXTIME(c.registered_at, %s) "
"FROM ( SELECT COUNT(1) AS inviters, joindate "
" FROM "
" ( SELECT DISTINCT(y.id) AS inviters, "
" FROM_UNIXTIME(y.registered_at, %s) AS joindate "
" FROM user_invites z "
" INNER JOIN users y ON y.id = z.inviter_id "
" WHERE z.created_at >= %s "
" ) a "
" GROUP BY a.joindate "
" ) b "
"INNER JOIN users c ON FROM_UNIXTIME(c.registered_at, %s) = b.joindate "
"WHERE c.registered_at BETWEEN %s AND %s "
"GROUP BY FROM_UNIXTIME(c.registered_at, %s) " )
args = ( timepattern, timepattern, datestart_int, timepattern,
datestart_int, dateend_int, timepattern )
cursor.execut(sql, args)
data = list(cursor.fetchall())
cursor.close()
connection.close()
Is there anyway I can reduce the duplication of my arguments? For example, timepattern is repeated 4 times and it gets hard to keep track of queries that are big.
sql = ( "SELECT IFNULL(b.inviters/COUNT(DISTINCT c.id),0), "
" FROM_UNIXTIME(c.registered_at, %s) "
"FROM ( SELECT COUNT(1) AS inviters, joindate "
" FROM "
" ( SELECT DISTINCT(y.id) AS inviters, "
" FROM_UNIXTIME(y.registered_at, %s) AS joindate "
" FROM user_invites z "
" INNER JOIN users y ON y.id = z.inviter_id "
" WHERE z.created_at >= %s "
" ) a "
" GROUP BY a.joindate "
" ) b "
"INNER JOIN users c ON FROM_UNIXTIME(c.registered_at, %s) = b.joindate "
"WHERE c.registered_at BETWEEN %s AND %s "
"GROUP BY FROM_UNIXTIME(c.registered_at, %s) " )
args = ( timepattern, timepattern, datestart_int, timepattern,
datestart_int, dateend_int, timepattern )
cursor.execut(sql, args)
data = list(cursor.fetchall())
cursor.close()
connection.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 args 作为参数字典并使用显式字符串插值 args (即
%(parameter_name)s
):try with this with using args as a parameters dictionnary and using explicit string interpolation args (ie
%(parameter_name)s
) :您可以将 args 作为 dict 给出,然后在查询中使用它,例如
%(name)s
例如You can give args as dict and then use it in query like
%(name)s
For example