代码之家  ›  专栏  ›  技术社区  ›  Carson Myers

这个mysql查询有问题吗?

  •  0
  • Carson Myers  · 技术社区  · 15 年前

    我第一次写存储过程,但它不工作。问题是我看不出它不起作用的原因。

    我正在运行phpmyadmin 2.8.2.4。我的MySQL版本是5.1。以下是查询的第一部分:

    create procedure under_user_type (in original_post int, out user_type int, out user_id longtext)
    begin
        if exists (
            select *
                from wp_postmeta as pm
                where pm.post_id = original_post
                and pm.meta_key = '_tdomf_original_poster_id'
        ) then
            set user_type = 0;
            select pm.meta_value
                into user_id
                from wp_postmeta as pm
                where pm.post_id = original_post
                and pm.meta_key = '_tdomf_original_poster_id';
    
        elseif exists ( ...
    

    我得到错误:
    #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 9

    第9行对应于 if exists ( ... ) then 部分。

    更新:

    如果我使用:

    create procedure under_user_type (in original_post int, out user_type int, out user_id longtext)
    begin
        if 1=1 then begin
            set user_type = 0;
            select pm.meta_value
                into user_id
                from wp_postmeta as pm
                where pm.post_id = original_post
                and pm.meta_key = '_tdomf_original_poster_id';
            end;
    

    再次更新:

    在上运行示例 this MySQL documentation page 还提供“检查“”附近的语法”错误。我尝试从查询中删除所有选项卡,但没有任何效果。

    第三次更新:

    我可以运行此查询:

    create procedure blah()
    begin
    end;
    

    但不是这个查询:

    create procedure blah2()
    begin
       if 1=1 then
       begin
       end;
       end if;
    end;
    

    当我得到同样的错误。

    4 回复  |  直到 15 年前
        1
  •  1
  •   Ken Bloom    15 年前

    以下对我有效:

    create procedure blah2()
    begin
      declare s int;
      if exists(select 1) then
        set s=1;
      end if;
    end;
    

    我认为您的问题(在第一个例子中,在您尝试进行所有实验之前)是您没有声明变量 user_type 因此,当MySQL在第9行遇到以前从未见过的变量名时,它会打印出一个(非常通用的)错误。

    (至于你的其他例子,你 不应该 if ... then begin ... end; 正确的语法是 if ... then ... elseif ... else ... end if )

        2
  •  0
  •   Ike Walker    15 年前

    当遇到第一个分号时,错误在第9行。

    如果要在过程主体中使用分号,则需要将分隔符设置为分号以外的其他值。

    以下是您最简单的示例如何做到这一点:

    DELIMITER $$
    
    create procedure blah2()
    begin
       if 1=1 then
       begin
       end;
       end if;
    end $$
    
    DELIMITER ;
    
        3
  •  0
  •   Carson Myers    15 年前

    问题是,phpmyadmin每次看到分号时都必须尝试拆分查询本身。这就是mysql cli所做的,这就是为什么在命令行上创建存储过程时需要更改分隔符的原因。但是,我的phpmyadmin版本(2.8.2.4)不允许我更改分隔符,所以我最后得到了一堆无用的错误消息。

    我在远程服务器上编写了一个带有文本区域的脚本,然后提交按钮,将文本区域的内容传递给 mysqli::multi_query . 这个函数允许MySQL处理分隔符,而不是试图将其本身拆分,因此创建过程在这方面起作用。

    另一个更简单的方法是使用MySQLWorkbench连接到数据库,如果数据库只允许从本地主机进行连接,则可能通过ssh进行连接。

        4
  •  -1
  •   Darcara    15 年前

    我不认为MySQL可以处理“如果存在”。 你可以试试

    declare testMe integer default (select ID from ... where ...);
    
    if testMe is not NULL then
    ...