【问题标题】:using results from a sql query in a python program in another sql query在另一个 sql 查询中使用 python 程序中的 sql 查询的结果
【发布时间】:2008-12-31 19:44:58
【问题描述】:

很抱歉我之前的问题非常模棱两可,但我想如果我得到这个问题的答案,我可以解决它。 在下面的程序中,我选择了数量少于数量的产品条形码。我想说,如果条形码(在冰箱表中)与另一个表(产品)中的条形码匹配,请将库存字段设置为 0。我遇到的问题是程序正在尝试匹配它找到的所有条形码在针对产品表中的单个条形码的查询中(这就是我的想法)。有谁知道该怎么做。太感谢了。林肯。

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)

【问题讨论】:

  • 您本可以就地纠正/编辑您之前的问题。
  • 您的问题记录清楚地表明您正在努力学习编程。如果这是真的,那么 SO 不适合您!尝试首先通过更适合该目的的教程和书籍来了解基础知识。
  • 对于 python,我推荐:www.greenteapress.com/thinkpython/thinkCSpy.pdf 对于数据库和 SQL,有:amazon.com/SQL-Practical-Developers-Kaufmann-Management/dp/… (tinyurl.com/86f56o)

标签: python sql


【解决方案1】:
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])

【讨论】:

  • 这个例子有效.. 只需要在for row in rows 后面加一个冒号。可能是因为上面的消息来自 2008 年(旧 Python 版本?)。
【解决方案2】:

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

什么时候做的

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

变量“行”现在是一个结果集(理解:数据库中的行列表) 类似 [(barcode1), (barcode2), (barcode3)..]

当你执行更新语句时

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()

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

【讨论】:

  • 请再次阅读您的最后一个问题及其答案,cmets。我不确定“你打算做什么”和“你认为会导致那个目的”这两件事是否一致。我建议再次阅读最后一个问题的 cmets 并重新考虑到底发生了什么。
猜你喜欢
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多