为啥 web2py 中两个逻辑相似的查询给出不同的结果?

Posted

技术标签:

【中文标题】为啥 web2py 中两个逻辑相似的查询给出不同的结果?【英文标题】:Why do two logically similar queries in web2py give different results?为什么 web2py 中两个逻辑相似的查询给出不同的结果? 【发布时间】:2016-05-11 13:52:42 【问题描述】:

我已经为此苦苦挣扎了一段时间,只是尝试随心所欲地改变条件。为什么它以一种方式工作而不是另一种?

关于这个表的定义:

db.define_table('bids',
                 Field('body', 'text', label="Application"),
                 Field('selected', 'string', requires=IS_IN_SET(['Yes', 'No']), readable=False, writable=False, default='No', widget=SQLFORM.widgets.radio.widget, label="Select this application"), 
                 Field('confirmed', 'string', requires=IS_IN_SET(['Yes', 'No']), readable=False, writable=False, default='No', widget=SQLFORM.widgets.radio.widget, label="Confirm acceptance"),
                 Field('delivered', 'string', requires=IS_IN_SET(['Yes', 'No']), readable=False, writable=False, default='No'),
                 Field('posted_on', 'datetime', readable=True, writable=False),
                 Field('posted_by', 'reference auth_user', readable=False, writable=False),
                 Field('job_id', 'reference jobs', readable=False, writable=False)
                 )

此查询产生正确的数据

query = db.bids.job_id == job_id and db.bids.delivered=='No' and db.bids.selected =='Yes' and db.bids.confirmed=='Yes'

虽然这个没有

query = db.bids.job_id == job_id and db.bids.selected =='Yes' and db.bids.confirmed=='Yes' and db.bids.delivered=='No'

【问题讨论】:

请参阅here 以了解代码示例的正确格式。 【参考方案1】:

这两个查询都不正确,因为您使用了and 而不是&(并且未能将每个条件括在括号中)。应该是:

((db.bids.job_id == job_id) & (db.bids.delivered == 'No') &
 (db.bids.selected == 'Yes') & (db.bids.confirmed == 'Yes'))

原始查询:

db.bids.job_id == job_id and db.bids.delivered=='No' and db.bids.selected =='Yes' and db.bids.confirmed=='Yes'

简单地等同于:

True and True and True and db.bids.confirmed == 'Yes'

在最终查询中只产生一个条件:

db.bids.confirmed == 'Yes'

【讨论】:

有道理。感谢您的额外解释 - 使它更加清晰。问题虽然,我需要把所有的 ((db.bids.job_id == job_id) & (db.bids.delivered == 'No') & (db.bids.selected == 'Yes') & (db .bids.confirmed == 'Yes')) 到 db() 或者是 db 函数外部的额外括号? 将其放入db() 时不需要外括号——我之所以这样做是因为它被分成了两行。

以上是关于为啥 web2py 中两个逻辑相似的查询给出不同的结果?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Snowflake 中这两个相似的查询具有非常不同的性能?

为啥这个 MySQL 存储函数给出的结果与在查询中进行计算不同?

Oracle SQL - 一个查询提供正确的输出,而另一个非常相似的查询却没有。为啥?

为啥我自己的逻辑回归实现与 sklearn 不同?

与子查询相比,为啥左外连接查询给出不同的结果?

MySQL 专家:为啥 2 个查询给出不同的“解释”索引使用结果?