简体   繁体   中英

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}.

PS: 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM