开发者

MySQL foreign key problem rails

I'm trying to add foreign keys to my table using the following code:

  constraint_name = "fk_#{from_table}_#{to_table}"
  execute %{ 
    CREATE TRIGGER #{constraint_name}_insert 
    BEFORE INSERT ON #{from_table} 
 开发者_如何转开发   FOR EACH ROW BEGIN
      SELECT 
        RAISE(ABORT, "constraint violation: #{constraint_name}")
      WHERE 
        (SELECT id FROM #{to_table} WHERE 
          id = NEW.#{from_column}) IS NULL
    END
  }

I'm getting the following error:

Mysql2::Error: Not allowed to return a result set from a trigger:  
    CREATE TRIGGER fk_brands_products_insert 
    BEFORE INSERT ON brands 
    FOR EACH ROW BEGIN
    SELECT 
      RAISE(ABORT, "constraint violation: fk_brands_products")
    FROM brands
    WHERE 
      (SELECT id FROM products WHERE id = NEW.brand_id) IS NULL;
      END;

What is wrong with my SQL script?


You can add a MySQL Foreign Key constraint like this:

ALTER TABLE #{from_table}
  ADD CONSTRAINT #{constraint_name} FOREIGN KEY
  (#{from_column}) REFERENCES #{to_table}(id)

This will constrain from_column on from_table to values in id in #{to_table}.

P.S: If you don't want to name the CONSTRAINT you can do this:

ALTER TABLE #{from_table}
  ADD FOREIGN KEY
  (#{from_column}) REFERENCES #{to_table}(id)


As the error states, a trigger is not allowed to return a result set. Even though you are raising a error, MySql doesn't like the SELECT statement. Try using a IF:

IF EXISTS(SELECT id FROM #{to_table} WHERE 
          id = NEW.#{from_column}) = 0 THEN
    RAISE(ABORT, "constraint violation: #{constraint_name}");
END IF;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜