简体   繁体   English

MySQL外键问题

[英]MySQL foreign key problem

I'm getting that error running on MySQL 5.5.8 我在MySQL 5.5.8上运行该错误

Mysql2::Error: 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 'WHERE 
      (SELECT id FROM products WHERE id = NEW.brand_id) IS NULL;
      EN' at line 6:  
    CREATE TRIGGER fk_brands_products_insert 
    BEFORE INSERT ON brands 
    FOR EACH ROW BEGIN
    SELECT 
      RAISE(ABORT, "constraint violation: fk_brands_products")
    WHERE 
      (SELECT id FROM products WHERE id = NEW.brand_id) IS NULL;
      END;

What could be wrong? 有什么事吗

Are you sure you can raise errors inside a query like that? 您确定可以在这样的查询中引发错误吗? I can't find it anywhere. 我在任何地方都找不到。 I think the proper way would be to select a COUNT or EXISTS and return the result of that INTO a variable. 我认为正确的方法是选择一个COUNT或EXISTS并将该结果返回到变量中。 Then, after the query, raise an error if the result doesn't meet your expectations. 然后,在查询之后,如果结果不符合您的期望,则会引发错误。

Something like this: 像这样:

SELECT count(id) INTO IDCOUNT FROM products WHERE id = NEW.brand_id;

Wouldn't it be better by the way to just add a real constraint? 仅仅添加一个真正的约束会更好吗? Or do you use a storage type that doesn't support that? 还是使用不支持该类型的存储类型?

我怀疑问题出在您的select语句中没有FROM子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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