简体   繁体   中英

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

The queries I have seen so far relate to INSERTING the results from the SELECT query - I do not wish to do that.

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

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 .

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

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