You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle表查询中如何实现两个列分别匹配不同列表的过滤?

实现方案

你可以直接在原有WHERE条件后追加AND逻辑关联type列的IN过滤规则即可,以下是两种可选实现方式:

方式1:沿用现有字符串拼接写法

直接新增type列表的拼接逻辑,给SQL的format方法传入两个拼接好的IN子句值即可:

office_list = ["aaa", "aab", "aac", "aad"]  
type_list = ["type1", "type2", "type3", "type4"]

# 分别拼接两个IN条件的字符串
office_in = "'" + "','".join([str(i) for i in office_list]) + "'"
type_in = "'" + "','".join([str(i) for i in type_list]) + "'"

sql = """
SELECT * 
  FROM (
        SELECT distinct(id) as id, 
               office, 
               cym,
               type
          FROM oracle1.table1
         WHERE office IN ({0})
           AND type IN ({1})
        ) 
""".format(office_in, type_in)

注意:该写法存在SQL注入风险,且如果列表元素本身包含单引号会导致SQL语法错误,仅推荐测试环境临时使用。

方式2:更安全的参数化查询写法(生产环境推荐)

使用Oracle官方驱动支持的参数化传参,避免注入风险和特殊字符语法问题,示例如下(以cx_Oracle驱动为例):

import cx_Oracle

# 你的现有Oracle连接 这里替换为你自己的连接逻辑
conn = cx_Oracle.connect("用户名/密码@主机:端口/服务名")

office_list = ["aaa", "aab", "aac", "aad"]  
type_list = ["type1", "type2", "type3", "type4"]

# 生成对应数量的参数占位符
office_placeholders = ','.join([f':office_{i}' for i in range(len(office_list))])
type_placeholders = ','.join([f':type_{i}' for i in range(len(type_list))])

# 组装SQL语句
sql = f"""
SELECT * 
  FROM (
        SELECT distinct(id) as id, 
               office, 
               cym,
               type
          FROM oracle1.table1
         WHERE office IN ({office_placeholders})
           AND type IN ({type_placeholders})
        ) 
"""

# 构造参数字典
params = {}
for idx, val in enumerate(office_list):
    params[f'office_{idx}'] = val
for idx, val in enumerate(type_list):
    params[f'type_{idx}'] = val

# 执行查询
cursor = conn.cursor()
cursor.execute(sql, params)
# 获取查询结果
res = cursor.fetchall()

内容的提问来源于stack exchange,提问作者Saara Jackman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:15:05