【问题标题】:Read multiple lists from python into an SQL query从 python 读取多个列表到 SQL 查询中
【发布时间】:2019-05-22 16:54:21
【问题描述】:

我有 3 个用户 ID 和时间范围列表(每个用户 ID 不同),我想为其提取数据。我正在通过 Python 查询 AWS redshift 数据库。通常,只有一个列表,我会做这样的事情:

sql_query = "select userid from some_table where userid in {}".format(list_of_users)

其中的用户列表是我想要的用户 ID 列表 - 比如说 (1,2,3...)

这很好用,但现在我需要以某种方式将它传递给(用户 ID、时间下限、时间上限)的三元组。例如 ((1,'2018-01-01','2018-01-14'),(2,'2018-12-23','2018-12-25'),...

我尝试了这个基本查询的各种版本

sql_query = "select userid from some_table where userid in {} and date between {} and {}".format(list_of_users, list_of_dates_lower_bound, list_of_dates_upper_bound)

但无论我如何在 format() 中构造列表,它都不起作用。我不确定这种方式是否可行,或者我是否应该遍历我的列表并为每个三元组重复调用查询?

【问题讨论】:

  • between 甚至可以处理 sql 中的列表吗?
  • 使用什么包连接到redshift?如果 psycopg2 查看此 QA stackoverflow.com/questions/8671702/…,它详细说明了如何填充 SQL IN 表达式。但是,您应该注意所需的类型是元组,而不是列表。但是,正如其他人在 cmets 中指出的那样,将多个元素传递到 BETWEEN 表达式的任一侧(作为列表、元组或其他方式)是荒谬的。考虑执行多个SELECT 语句,可能由某种UNION 连接。

标签: python sql amazon-redshift


【解决方案1】:

假设值列表如下所示:

list_of_users = [1,2], 
list_of_dates_lower_bound = ['2018-01-01', '2018-12-23']
list_of_dates_lower_bound = ['2018-01-14', '2018-12-25']

格式化后的 sql 将是:

select userid from some_table where userid in [1,2] and date between ['2018-01-01', '2018-12-23'] and ['2018-01-14', '2018-12-25']

这个结果应该不是你想的那样,它只是一个无效的sql,between的操作数应该是标量值。

我建议遍历列表,并将单个值传递给占位符。

【讨论】:

    【解决方案2】:

    您可以通过使用在特定范围内进行选择

    select col from table where col between range and range;
    

    你的情况可能是

    select userid from some_table where date_from between yesterday and today;
    

    甚至

    select userid from some_table where date_from >= yesterday and date_from <= today;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多