代码之家  ›  专栏  ›  技术社区  ›  marc lincoln

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

  •  0
  • marc lincoln  · 技术社区  · 16 年前

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

    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)
    
    2 回复  |  直到 11 年前
        1
  •  5
  •   Adam Peck    16 年前
    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])
    
        2
  •  4
  •   JV.    16 年前

    这更多的是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。