如何基于Python字典动态生成SELECT查询语句?
动态生成带INNER JOIN的SQL查询语句
思路拆解
要实现需求,核心要处理三个部分:
- 收集所有非主键字段作为SELECT目标
- 动态生成和主表关联的INNER JOIN语句
- 组合各部分成完整SQL
完整代码实现
my_dictionary = { "sec_identifier": ["ukey", "date", "id_1"], "sec_profile": ["ukey", "date", "amount", "name"], "sec_sch": ["ukey", "date", "interest", "price"] } # 定义固定主键字段 fixed_cols = ['ukey', 'date'] # 指定主表(也可以改成动态取字典第一个表:main_table = next(iter(my_dictionary.keys()))) main_table = "sec_profile" # 生成表别名:取下划线分割后每个单词的首字母拼接 def get_table_alias(table_name): return ''.join(word[0] for word in table_name.split('_')) # 生成SELECT字段列表 select_fields = [] for table, cols in my_dictionary.items(): alias = get_table_alias(table) # 只保留非主键的列 non_fixed_cols = [col for col in cols if col not in fixed_cols] select_fields.extend([f"{alias}.{col}" for col in non_fixed_cols]) # 生成INNER JOIN语句 main_alias = get_table_alias(main_table) join_clauses = [] for table in my_dictionary.keys(): if table == main_table: continue alias = get_table_alias(table) join_clause = f"INNER JOIN {table} {alias} ON ({main_alias}.ukey, {main_alias}.date) = ({alias}.ukey, {alias}.date)" join_clauses.append(join_clause) # 拼接完整SQL select_part = ", ".join(select_fields) from_part = f"FROM {main_table} {main_alias}" join_part = "\n".join(join_clauses) sql = f"SELECT {select_part} {from_part}\n{join_part}" print(sql)
代码说明
- 主键与主表定义:先明确固定主键
ukey和date,指定关联的主表(示例用sec_profile,也可动态取第一个表)。 - 表别名生成:按表名的下划线分割取首字母拼接,和示例中的
si、sp、sc规则完全匹配。 - SELECT字段收集:遍历所有表,过滤掉主键字段,按
别名.列名格式整理查询字段。 - 动态JOIN生成:遍历除主表外的所有表,每个表生成一条INNER JOIN语句,用主表主键和当前表主键做关联。
- SQL拼接:把SELECT、FROM、JOIN三部分拼接成完整语句,格式和示例一致。
运行结果
执行代码后会输出和你期望完全一致的SQL:
SELECT si.id_1, sp.amount, sp.name, sc.interest, sc.price FROM sec_profile sp INNER JOIN sec_identifier si ON (sp.ukey, sp.date) = (si.ukey, si.date) INNER JOIN sec_sch sc ON (sp.ukey, sp.date) = (sc.ukey, sc.date)
扩展说明
如果字典中只有一个表,代码会自动跳过JOIN部分,生成简单的SELECT ... FROM ...语句,适配不同场景。
内容的提问来源于stack exchange,提问作者Sachin
相关产品推荐
相关产品推荐

