问题
I read several examples that show how pymysql "select in" should work. So, this example works just fine:
sql_select = 'SELECT a.user_id, AVG(a.rcount) AS \'average\' ' \
'FROM (SELECT user_id, item_id, count(*) AS rcount ' \
'FROM submission AS qsm ' \
'JOIN metadata as qm ' \
'ON qsm.item_id = qm.id ' \
'WHERE qsm.item_id NOT IN (1, 2, 5, 6, 7, 147, 148) ' \
'AND DATE(FROM_UNIXTIME(submission_time)) BETWEEN %s AND %s ' \
'AND qm.type != \'survey\' ' \
'GROUP BY user_id, item_id ' \
'ORDER BY user_id) a ' \
'GROUP BY a.user_id'
args = [course_start, course_end]
cur.execute(sql_select, args)
But, I would also like to add another argument for this "NOT IN" part. The problem here is that this list is variable, so not quite sure how to handle this one.
回答1:
With PyMySQL version 0.7.9:
cells = ('cell_1', 'cell_2')
cursor.execute('select count(*) from instance where cell_name in %(cell_names)s;', {'cell_names': cells})
# or alternately
cursor.execute('select count(*) from instance where cell_name in %s;', [cells])
The PyMySQL execute documentation describes the two possible forms:
If args is a list or tuple, %s can be used as a placeholder in the query.
If args is a dict, %(name)s can be used as a placeholder in the query.
来源:https://stackoverflow.com/questions/39334484/pymysql-select-in-with-variable-number-of-parameters