【问题标题】:Query SyntaxError [closed]查询语法错误 [关闭]
【发布时间】:2015-12-07 09:50:15
【问题描述】:

我对 SQL 还很陌生。我只是想生成一个表格并在特定条件下填写一些值。您在此查询中看到任何语法错误吗?非常确定错误在 case 语句中,因为没有 case 语句,表格生成就好了。

q = "select tbuc.csId, tbui.role_type, 
(case when tbui.role_type = "ROLE_USER" then 1 else 0 end) as
assignment_submitted FROM tb_user_click tbuc, tb_user_info tbui WHERE 
tbui.user_id = tbuc.uId and tbuc.csId = tbui.class_section_id;"

也试过用IIF,报错如下:

File "1.py", line 118
q = "select tbuc.csId, tbui.role_type,IIF(role_type = "ROLE_USER", 1, 0) 
as assignment_submitted FROM tb_user_click tbuc, tb_user_info tbui 
WHERE tbui.user_id = tbuc.uId and tbuc.csId = tbui.class_section_id;"
SyntaxError: invalid syntax

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误在问题本身中重现它所需的最短代码。没有明确的问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
  • 语法高亮应该放弃这个。
  • 可能是 ROLE_USER 周围未转义的双引号
  • 1:st 查询是有效的 ANSI SQL 语法。 UID 是产品特定的后缀词。双引号“uId”是安全的。 2:nd 查询包含产品特定的 IIF 函数。
  • 但问题在于 ROLE_USED 周围的双引号。双引号用于对象名称(例如列)。字符串文字有单引号,例如'ROLE_USED'。

标签: sql case


【解决方案1】:

要么用单引号,比如

q = "select tbuc.csId, tbuc.uId, tbuc.cId, tbui.role_type, tbuc.time as login_date"
    + ", tbuc.sessId, (case when tbui.role_type = 'ROLE_USER' then 1 else 0 end) "
    + "as assignment_submitted FROM tb_user_click tbuc, tb_user_info tbui WHERE "
    + "tbui.user_id = tbuc.uId and tbuc.csId = tbui.class_section_id;"

或者转义双引号,比如

q = "select tbuc.csId, tbuc.uId, tbuc.cId, tbui.role_type, tbuc.time as login_date"
    + ", tbuc.sessId, (case when tbui.role_type = \"ROLE_USER\" then 1 else 0 end"
    + ") as assignment_submitted FROM tb_user_click tbuc, tb_user_info tbui WHERE "
    + "tbui.user_id = tbuc.uId and tbuc.csId = tbui.class_section_id;"

或者(假设您的客户端支持)使用绑定参数,例如

q = "select tbuc.csId, tbuc.uId, tbuc.cId, tbui.role_type, tbuc.time as login_date"
    + ", tbuc.sessId, (case when tbui.role_type = ? then 1 else 0 end) "
    + "as assignment_submitted FROM tb_user_click tbuc, tb_user_info tbui WHERE "
    + "tbui.user_id = tbuc.uId and tbuc.csId = tbui.class_section_id;"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多