处理WHERE子句中的空数组

时间:2016-07-10 19:21:15

标签: arrays postgresql python-2.7 psycopg2

我尝试使用接收名为public function getDeleteQuote($quote_id) { $quote = Quote::find($quote_id); $author_id = $quote->author_id; $total_quote = DB::table('quotes')->where('author_id' , $author_id)->count(); $author_deleted = false; if($total_quote === 1) { $auth_deleted = DB::table('authors')->where('id' , $author_id)->delete(); $author_deleted = true; } $quote->delete(); $msg = $author_deleted ? 'Quote And Author Deleted !' : 'Quote Deleted !' ; return redirect()->route('home')->with([ 'success' => $msg ]); } 的变量的函数执行查询:

date

def initial_query(date): # Some code verifying the correctness of the date query = """ SELECT some_fields FROM tableA A INNER JOIN tableB B on A.transaction_id = B.transaccion_id WHERE A.action_id in (1,2,3) AND A.test = false AND (maf.client_id = ANY(%(clients)s::bigint[]) OR maf.merchant_code = ANY(%(merchants)s::varchar[])) AND maf.country_iso = ANY(%(countries)s) AND maf.date >= '{date}' """ return query.format(date=date) 内,我通过以下方式使用main()功能:

initial_query(date)

其中cursor.execute(initial_query(starting_date), {'countries': countries, 'clients': client_ids, 'merchants': merchant_codes }) 是psycopg2游标,变量cursor在某些情况下可以是空列表(但不是全部)。如果我将查询传递给空列表,我将不会获得任何结果,因为任何行

countries, clients, merchants

总是会返回false。所以我想知道是否有一些方法可以使用SQL代码来修改initial_query中的查询,以避免这些行总是返回false,因为传递给游标的任何列表都是空的。

1 个答案:

答案 0 :(得分:0)

我解决了它添加一个布尔变量,为每个案例提供两个不同的查询

def initial_query(date, is_segment=False):

# Some code verifying the correctness of the date
     if is_segment:
        query = """   SELECT some_fields
                        FROM tableA A
                  INNER JOIN tableB B on A.transaction_id = B.transaccion_id
                       WHERE A.action_id in (1,2,3)
                         AND A.test = false
                         AND (maf.client_id = ANY(%(clients)s::bigint[]) OR maf.merchant_code = ANY(%(merchants)s::varchar[]))
                         AND maf.date >= '{date}'
                 """
    else:
        query = """   SELECT some_fields
                        FROM tableA A
                  INNER JOIN tableB B on A.transaction_id = B.transaccion_id
                       WHERE A.action_id in (1,2,3)
                         AND A.test = false
                         AND maf.country_iso = ANY(%(countries)s)
                         AND maf.date >= '{date}'
                 """
    return query.format(date=date)