简体   繁体   中英

Mysql - Check if row exists

I want to insert a row only if it's parent exists in another table.

thread1 table

id | content      | 
1  |  Hello World |
2  |  Bye World   |

thread2 table

id | content     | 
1  |  Naruto     |
2  |  DragonBallz|

comment table

id | thread_id| thread_type | content    |
1  |    1     |     thread1 |    hellow  |
2  |    1     |     thread2 |    bye-bye |

Now if i do

INSERT INTO comment(thread_id,thread_type,content)VALUES('3','thread2','Whatever');

it should fail because 3 does not exists in thread2 table.

This is possible by checking from thread table. But is it possible without it ? Without doing an extra query ?

Update

Tables above has been updated. the thread_type refers to the table thread1 & thread2

Creating a foreign key between the two tables, using thread(id) as the parent and comment(thread_id) as the child, should do the trick.

This is the command you should run -

ALTER TABLE comment
    ADD FOREIGN KEY
    (thread_id)
    REFERENCES thread (id)

Try this:

INSERT INTO comment ('3','thread2','Whatever')  
select t2.id,0,0
from thread2 t2
where t2.id = '3';  

I am assuming, id in your comment table is a primary key and auto incremented.
Above query will select id from thread2 table depending on your thread type. If id is found in thread2 table, it will insert a new row else insert zero row as zero rows are selected from parent table.

Hope it helps :)

This may do that:

INSERT INTO comment(thread_id,thread_type,content)
(select id as thread_id, thread_type, '[content]' as content
from ((select id,'thread1' as thread_type from thread1)
union 
(select id,'thread2' as thread_type from thread2 )) threads
where threads.id=[thread_id] and threads.thread_type ='[thread_type]')

As in your sample

[thread_id]=3
[thread_type]=thread2
[content]=Whatever

So if there is such a parent it will be insert a row, otherwise won't insert anything.

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