如何在Python的SQL语句中使用变量和OR连接?

安托万·科平

我在命名列表中有一个Ids列表res,在将结果保存到数组中之前,我想在SQL查询中逐行使用WHERE条件:

                              ids
grupos                           
0       [160, 161, 365, 386, 471]
1                      [296, 306]

这是我尝试在SQL查询中插入的内容:

listado = [None]*len(res)
# We store the hashtags that describes the best the groups
# We iterate on the people of a group to construct the WHERE condition
print "res : ", res
for i in (0,len(res)):        

conn = psycopg2.connect(**params)
cur = conn.cursor()

listado = [None]*len(res)
for i in (0,len(res)):        
    print "res[i:p] : ", res.iloc[i]['ids']
    cur.execute("""SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
    -- join para que las publicidades/eclipses que gusta un usarios estan vinculadas con las de la tabla de correspondencia con los hashtag
    INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
    -- join para que los usarios  estan vinculados con los de la tabla de correspondencia con los hashtag
    LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
    -- recobremos los "me gusta"
    WHERE subscriber_hastag.subscriber_id in (%s)
    GROUP BY subscriber_hashtag.hashtag_id
        ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))

    n = cur.fetchall()
    listado[i] = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]

数据可重现

提供更多数据信息:

subscriber_id hashtag_id
160           345
160           347
161           345
160           334
161           347
306           325
296           362
306           324
296           326
161           322
160           322

输出在这里应该像:

{0:[324,1],[325,1],[326,1],[362,1], 1 : [345,2],[347,2],[334,1]}

当前错误信息

错误:对输入进行标记化时发生意外错误以下回溯可能已损坏或无效错误消息是:('EOF in multi-line string',(1,50))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-f7c3c5b81303> in <module>()
     39         WHERE subscriber_hastag.subscriber_id in (%s)
     40         GROUP BY subscriber_hashtag.hashtag_id
---> 41             ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))
     42 
     43         n = cur.fetchall()

TypeError:并非在字符串格式化期间转换了所有参数

IljaEverilä

看看元组适应

Python元组被转换为适合SQL IN运算符的语法,并表示复合类型:

将id作为元组查询参数传递,因此要执行的参数是id元组的1元组,并在周围加上手动括号%s目前,您(res.iloc[i]['ids'])不过是多余括号中的序列表达式,因此execute()将其用作参数序列,这会导致TypeError异常;您的参数序列具有比查询具有占位符更多的参数。

试试吧(tuple(res.iloc[i]['ids']),)注意逗号,忽略它是一个很常见的错误总而言之:

cur.execute("""SELECT COUNT(swipe.eclipse_id), 
subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE subscriber_hashtag.subscriber_id in %s
GROUP BY subscriber_hashtag.hashtag_id
    ORDER BY COUNT(swipe.eclipse_id) DESC;""",
(tuple(res.iloc[i]['ids']),))

您的for循环有点奇怪,因为您要遍历2元组(0, len(res))也许你的意思是range(len(res))您还可以遍历“熊猫系列”:

for i, ids in enumerate(res['ids']):
    ...
    cur.execute(..., (tuple(ids),))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python的SQL语句中使用变量?

如何在Oracle PL-SQL中的select语句中使用变量

如何在switch语句中使用成员变量?

如何在SELECT语句中使用postgres变量?

如何在case语句中使用优先值或在函数中的sql语句中的case语句中设置变量

如何在sql和php中的“ SELECT DISTINCT CASE WHEN”语句中使用“ ORDER BY”语句?

如何在更新语句中使用SQL变量递增

如何在switch语句中使用变量

如何在“ if”语句中使用代数变量?

比较变量时如何在where语句中使用CASE和IN

如何在bash脚本中连接字符串以在SQL语句中使用?

如何在创建表语句中使用变量

如何在XMLSlurper语句中使用变量引用

如何在SELECT语句中使用变量?

SQL Server:如何在insert语句中使用if语句

如何在EXECUTE格式语句中使用timestamp变量

如何在Set @var = Select语句中使用变量

如何在If then语句中使用特殊的shell变量

如何在SQL INSERT语句中使用PHP / HTML中的变量

如何在sql create语句中使用变量名作为表名

如何在sql触发器中使用插入语句中的变量

如何在Oracle的PL/SQL语句中使用php变量

如何在sql语句中使用distinct和group

如何在IF语句中使用Jenkins本地定义的变量?

如何在左连接语句中使用替换

如何在sql语句中使用变量

如何在单个 if 语句中使用调用多个变量?

如何在 Python 中使用 IN 语句在 SQL 语句中使用变量

如何在 SQL Server 连接语句的右选择语句中的 where 子句中使用左表中的列