简体   繁体   English

Mysql,如果表A中存在外键,则将新记录插入表B

[英]Mysql, Insert new record into table B if foreign key exists in table A

There are a few similar questions on here.这里有几个类似的问题。 None provide a solution.没有一个提供解决方案。 I would like to INSERT a NEW record into table B , but only if a foreign key exists in table A .我想在表B 中插入一条记录,但前提是表A 中存在外键。 To be clear, I do not wish to insert the result of a select.需要明确的是,我不想插入选择的结果。 I just need to know that the foreign key exists.我只需要知道外键存在。

INSERT INTO tableB (tableA_ID,code,notes,created) VALUES ('24','1','test',NOW())
        SELECT tableA_ID FROM tableA WHERE tableA_ID='24' AND owner_ID='9'

Clearly, the above does not work.显然,上述方法不起作用。 But is this even possible?但这甚至可能吗? I want to insert the NEW data into tableB, only if the record for the row in tableA exists and belongs to owner_ID.我想将新数据插入 tableB,仅当 tableA 中行的记录存在且属于 owner_ID 时。

The queries I have seen so far relate to INSERTING the results from the SELECT query - I do not wish to do that.到目前为止,我所看到的查询与从 SELECT 查询中插入结果有关 - 我不希望这样做。

Try this:试试这个:

INSERT INTO tableB (tableA_ID,code,notes,created) 
SELECT id, code, notes, created
FROM ( SELECT '24' as id, '1' as code, 'test' as notes, NOW() as created) t
WHERE EXISTS 
(
   SELECT tableA_ID 
   FROM tableA 
   WHERE tableA_ID='24' AND owner_ID='9'
)

I know it's a pretty much old answered question but it's highly ranked now in google search results and I think some addition may help someone in the future.我知道这是一个很老的回答问题,但它现在在谷歌搜索结果中排名很高,我认为一些补充可能在未来对某人有所帮助。

In some DB configuration, you may want to insert a row in a table that have two or more foreign keys.在某些数据库配置中,您可能希望在具有两个或多个外键的表中插入一行。 Let's say we have four tables in a chat application : Users , Threads , Thread_Users and Messages假设我们在聊天应用程序中有四个表: UsersThreadsThread_UsersMessages

If we want a User to join a Thread we'll want to insert a row in Thread_Users in wich have two foreign keys : user_id , thread_id .如果我们想让一个User加入一个Thread我们需要在Thread_Users中插入一行, Thread_Users有两个外键: user_idthread_id

Then, we can use a query like this, to insert if both foreign keys exists, and silently fail otherwise :然后,我们可以使用这样的查询,如果两个外键都存在,则插入,否则静默失败:

INSERT INTO `thread_users` (thread_id,user_id,status,creation_date)
SELECT 2,3,'pending',1601465161690 FROM (SELECT 1 as nb_threads, 1 as nb_users) as tmp 
WHERE tmp.nb_threads = (SELECT count(*) FROM `threads` WHERE threads.id = 2)
      AND tmp.nb_users = (SELECT count(*) FROM `users` WHERE users.id = 3)

It's a little verbose but it does the job pretty well.它有点冗长,但它做得很好。

Application-side, we just have to raise an error if affectedRows = 0 and maybe trying to see which of the keys doesn'nt exists.应用程序方面,我们只需要在受影响的行 = 0 时引发错误,并且可能会尝试查看哪些键不存在。 IMHO, it's a better way to do the job than to execute two SELECT queries and THEN execute the INSERT especially when an inexistent foreign key probability is very low.恕我直言,这是比执行两个 SELECT 查询然后执行 INSERT 更好的方法,尤其是当不存在的外键概率非常低时。

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

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