使用尚未创建的外键插入 mySQL 表
好吧,我有两张桌子。他们都有钥匙。我有另一个引用这两个键的表。当我添加到第三个表时,如果前两个表中不存在任何一个键,我如何才能做出约束,它不会将该元组插入到第三个表中。我正在 phpMyAdmin 中插入。谢谢。
Okay I have two tables. They both have keys. I have another table that references both keys. How can I make a constraint when I add into that third if either of the keys don't exist in the first two tables it won't insert that tuple into the third table. I am inserting in phpMyAdmin. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:
抱歉误读了您的问题。 Mysql 仅支持某些引擎的约束。 InnoDB 是我所知道并经常使用的一种,但其他的我可能真的不确定。因此,对于 inno DB,您需要以下模式:
这将禁用 FK 检查,因为 sql 语句会反映出来,直到您执行插入之后。如果我没记错的话,它会在重新打开后检查按键。因此,您可能需要使用事务,以便在您犯了错误并且密钥最终不匹配时可以回滚。否则你可能会得到部分数据,这一点也不有趣:-)
EDIT:
Sorry for misreading your question. Mysql only supports contraints with certain engines. InnoDB is the one i know of and generally use, but other might im really not sure. So with inno DB youd need th following schema:
This will disable the FK checks ast the sql statements reflect until after you have performed your inserts. If i remember correctly It will then check the keys once turned back on. Because of this you may want to use a transaction so that you can roll back if you have made a mistake and the keys dont match up in the end. Otherwise you might have partial data which is never fun :-)
我不知道约束,但您可以使用此插入查询:
INSERT INTO TAB3(TAB3_key1,TAB3_key2) SELECT val1,val2 FROM TAB1 JOIN TAB2 ON EXISTS (SELECT * FROM TAB1 JOIN TAB2 ON TAB1_key=val1 AND TAB2_key=val2) LIMIT 1;
其中 val1,val2 - 要插入的值。
i don't know about constraint but you may use this insert query:
INSERT INTO TAB3(TAB3_key1,TAB3_key2) SELECT val1,val2 FROM TAB1 JOIN TAB2 ON EXISTS (SELECT * FROM TAB1 JOIN TAB2 ON TAB1_key=val1 AND TAB2_key=val2) LIMIT 1;
where val1,val2 - values that you want to insert.