使用IF启动mysql查询

使用IF启动mysql查询,mysql,Mysql,根据mysql网站,我应该能够用if语句开始查询 IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF 但是当我尝试这个查询时 if (count(1) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = 'dbname' AND TAB

根据mysql网站,我应该能够用if语句开始查询

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
但是当我尝试这个查询时

if (count(1)
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME='tblname'
AND CONSTRAINT_NAME = 'con_name')
then
alter table table drop foreign key constraint_name;
end if
我得到一个语法错误,说我在“IF”附近有错误的语法,mysql workbench突出显示IF语法错误,意外的IF


我试过使用begin if,省略了begin if和end if,但错误总是一样的。

如果两个表都有相同的结构(或者使用相同的结构而不是*),您可以通过这种方式使用并集来实现这一点

select * from sometable WHERE (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME='tblname' AND CONSTRAINT_NAME = 'con_name') = 1
    union all
select * from anothertable WHERE (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME='tblname' AND CONSTRAINT_NAME = 'con_name') IS NULL

或者,您可以通过使用存储过程(使用与您编写的几乎相同的synbtax)来实现这一点。

如果或在条件语句外,则不能使用,除非它们包含在
开始
-
结束
的代码块中。因此,db引擎在您的语句中抛出了一个错误

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
要使语句正常工作,还需要一个存储过程和对语句的一些更改

示例

delimiter //

drop procedure if exists drop_constraint //

create procedure drop_constraint( 
    in dbName varchar(64), 
    in tableName varchar(64),
    in constraintName varchar(64) )
begin
    declare cnt int default 0;

    select count(1) into cnt 
      from INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
      where 
        table_schema = dbName
        and table_name = tableName
        and constraint_name = constraintName;

    -- now check if any found
    if ( cnt > 0 ) then -- if found some
        -- now, execute your alter statement
        -- include your alter table statement here
    end if;
end;
//

delimiter ;
使用上述步骤,可以检查并删除约束

mysql> call drop_constraint( 'test', 'my_table', 'fk_name' );

您想要实现的是在前端完成的,而不是在后端。在代码段的正下方,有一个IF语句用于存储程序,它实现了一个基本的条件构造。你必须把它包装成一个函数。也许你可以用?