MySQL外键问题导轨

时间:2011-02-21 16:43:59

标签: mysql ruby-on-rails

我正在尝试使用以下代码将外键添加到我的表中:

  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
  }

我收到以下错误:

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;

我的SQL脚本有什么问题?

2 个答案:

答案 0 :(得分:1)

您可以像这样添加MySQL外键约束:

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

这会将from_table上的from_column限制为#{to_table}中id的值。

P.S:如果你不想命名CONSTRAINT,你可以这样做:

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

答案 1 :(得分:0)

如错误所述,不允许触发器返回结果集。即使您提出错误,MySql也不喜欢SELECT语句。尝试使用IF

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