在另一个sql查询中使用python程序中sql查询的结果

2024-03-28 17:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉我之前的问题很含糊,但我想如果我得到这个问题的答案,我可以解决它。 在下面的程序中,我选择了数量小于数量的产品的条形码。我想说的是,如果条形码(在冰箱表中)与另一个表(产品)中的条形码匹配,那么将stock字段设置为0。我得到的问题是,程序正试图将它在查询中找到的所有条形码与products表中的单个条形码相匹配(这就是我的想法)。有人知道该怎么做吗。万分感谢。林肯。

import MySQLdb

def order():
    db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
    cursor = db.cursor()
    cursor.execute('select barcode from fridge where amount < quantity')
    db.commit()
    row = cursor.fetchall()
    cursor.execute('update products set stock = 0 where barcode = %s', row)

Tags: 答案程序executedb数量产品stockwhere
2条回答

这更多的是SQL查询,而不是Python,但我还是会尝试回答: (我没有使用过MySQL,但使用过PostgreSQL,所以这里对事物的解释可能略有不同)。

当你这么做的时候

cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
row = cursor.fetchall()

变量“row”现在是一个resultset(要理解:来自数据库的行列表) 类似于[(条形码1),(条形码2),(条形码3)…]

当您执行update语句时

cursor.execute('update products set stock = 0 where barcode = %s', row)

这就变成了:

update products set stock = 0 where barcode = [(barcode1), (barcode2), (barcode3)..]

这不是正确的SQL语句。

你应该这样做:

cursor.execute('update products set stock = 0 where barcode in (%s)', ','.join([each[0] for each in row]))

或者更好的是,优化的东西:

import MySQLdb

def order():
    db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
    cursor = db.cursor()
    cursor.execute('update products set stock = 0 where barcode in (select barcode from fridge where amount < quantity)')
    db.commit()

好吧,要添加更多内容,在select查询之后而不是update查询之后有一个db.commit(),这是一个基本的错误。Select是等幂的,不需要提交,而Update需要提交。我强烈建议您在继续之前检查一些SQL。

UPDATE products SET stock = 0 WHERE barcode IN ( 
    SELECT fridge.barcode FROM fridge WHERE fridge.amount < fridge.quantity );

我知道这并不能完全回答这个问题,但是不需要两个SQL语句。

要在python中执行此操作:

import MySQLdb

def order():
    db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
    cursor = db.cursor()
    cursor.execute('select barcode from fridge where amount < quantity')
    db.commit()
    rows = cursor.fetchall()
    for row in rows
        cursor.execute('update products set stock = 0 where barcode = %s', row[0])

相关问题 更多 >