根据最小值和最大值确定布尔值

2024-10-01 04:16:01 发布

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

现在我有了表1中的最小值和最大值,它定义了一个值的范围。表2中有一个布尔列,其值由表1中的最小值和最大值确定。如果实际数字在范围内,则值为F(表示没有问题),反之亦然。运行代码后,只有列的前两行显示为false。我不知道我的密码怎么了。我的for循环块代码如下。其中,records1为表2中的实际值,records2和records3分别为表1中的最小值和最大值。我使用这个forloop语句来获取三组数字的单个记录,然后在其中的if语句中,通过检查record1是否在min(record2)和max(record3)值之间来确定布尔列的每个值。在

    conn = psycopg2.connect(conn_string)
    # conn.cursor will return a cursor object, you can use this cursor to perform queries

    #get the actual number
    curs1 = conn.cursor()
    statement='SELECT value FROM table2'
    curs1.execute(statement)
    records1=curs1.fetchall()

    #get the minimum number
    curs2 = conn.cursor()
    statement2='SELECT min FROM table1'
    curs2.execute(statement2)
    records2=curs2.fetchall()

    #get the maximum number
    curs3 = conn.cursor()
    statement3='SELECT max FROM table1'
    curs3.execute(statement3)
    records3=curs3.fetchall() 


    for record1 in records1:
        for record2 in records2:
            for record3 in records3:
                while record1 >= record2 and record1 <=record3::
                    statement4='UPDATE table2 SET column = false WHERE record1 >=   record2 and record1 <= record3'
                    curs4 = conn.cursor()
                    curs4.execute(statement4)

                else:
                    statement5='UPDATE table2 SET column = true WHERE record1 <= record2 or record1 >= record3'
                    curs5 = conn.cursor()
                    curs5.execute(statement5)
                conn.commit()
                conn.close()

有人能指出我错在哪里吗?提前Tks


Tags: thenumberforexecutegetconnselectcursor
2条回答

注意range在python中的工作方式。。。在

>>> range(1,5)
[1, 2, 3, 4]
>>>

你最好做一个比较陈述:

if record2 <= record1 <= record3:

另外,从它看来,您正在用语句而不是比较中的记录行来更新整个表。在

我认为for循环是多余的,相反,sql语句应该考虑您要完成的任务,或者需要为行传递一个id并将其用于WHERE子句。在

我用下面的语句解决了这个问题:

 statement1='UPDATE table2 SET column= false WHERE value >= (SELECT min FROM table1 WHERE
 table1.common_name=table2.common_name) AND value <=(SELECT max FROM table1 WHERE 
 table1.common_name=table2.common_name)'

。。。在

我没有在forloop中使用variable,而是使用select语句,在语句中我使用WHERE子句定义min和max的相应记录。在

相关问题 更多 >