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

如何为字典中每个属性添加反引号以生成正确SQL查询?

问题:SQL查询构建时无法为每个属性单独添加反引号

我尝试将字典中的每个属性用反引号包裹来构建SQL查询,但多次尝试后,所有属性仅在首尾出现反引号,无法实现每个属性单独被反引号包裹的效果。

代码示例

base_datatypes = [
    {"datatype": 1, "data_type_name": "SomeValue"},
    {"datatype": 2, "data_type_name": "DateTime"},
]

datatype_attributes_dict = {
    "DateTime": "'Year','Month','Day'"
}

created_base_attributes = [
    "attribute_DateTimeTable",
    "attribute_SomeDictionary"
]

select_clause = "SELECT COALESCE(t1.sys_id, t2.sys_id) AS PK"

for i, view in enumerate(created_base_attributes, start=1):
    data_type_name = next((item["data_type_name"] for item in base_datatypes if f"attribute_{item['data_type_name'].lower()}" == view), None)
    if data_type_name:
        attributes = datatype_attributes_dict.get(data_type_name, "")
        if attributes:
            columns = [f"`{attr.strip()}`" for attr in attributes.replace("'", "").split(",")]
            select_clause += ", " + ", ".join(columns)

print(select_clause)

当前输出(仅展示属性部分)

``Year,Month,Day``

期望输出(仅展示属性部分)

`Year`, `Month`, `Day`

解决方案

问题根源在于视图名称的匹配逻辑不生效,导致属性处理代码根本没执行,你看到的输出并非这段代码生成的。

  1. 修正匹配逻辑:
    当前判断条件f"attribute_{item['data_type_name'].lower()}" == view会生成attribute_datetime,但你的created_base_attributes里是attribute_DateTimeTable,两者不匹配。可以改成:

    # 用startswith判断,忽略视图名称后缀
    data_type_name = next((item["data_type_name"] for item in base_datatypes if view.startswith(f"attribute_{item['data_type_name'].lower()}")), None)
    

    或者直接把created_base_attributes里的元素改为attribute_datetime,和拼接后的字符串完全匹配。

  2. 确认属性处理代码:
    你写的属性处理逻辑columns = [f"{attr.strip()}" for attr in attributes.replace("'", "").split(",")]是正确的,只要匹配逻辑生效,就能生成每个属性单独带反引号的结果,最终得到你期望的输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 23:12:14