【问题标题】:The function processes the sql request函数处理sql请求
【发布时间】:2020-07-09 12:06:54
【问题描述】:

函数处理sql请求。它接收参数,其中一个可以是“null”或值(uuid), 我需要将此值添加到位置。 但是有一个问题,因为用null “其中 param 为 null”,但值为“where param = value”

例子



sql = '''select name from table where param = %s '''
def run_sql(param=None):
    a = db_api(sql, param)
    

【问题讨论】:

  • 你不能用if/else 吗?
  • 你能告诉我我的例子吗?
  • 难道你不知道如何使用if/else 并针对不同的数据类型运行两个不同的查询吗?
  • if param == "null" : sql = '''select name from table where param is %s ''' else: sql = '''select name from table where param = %s '''
  • 我不考虑这种方法,因为工作的 sql 查询比示例中的要大得多。我想避免代码重复。

标签: python sql postgresql flask psycopg2


【解决方案1】:
select name from table where param is not distinct from %s

在 sql 中,null = nullnull <> null 的计算结果始终为 false,因为 null 值被视为未知,不能被视为彼此相等或不相等。

但是两个null 值彼此没有区别,所以null is not distinct from null 的计算结果为true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多