Mysql - check if row exists

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

table thread1

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

table thread2

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 must fail because it 3does not exist in the table thread2.

This can be checked from the thread table. But is it possible without him? No additional request?

Refresh

The tables above have been updated. thread_typerefers to the table thread1andthread2

+4
source share
3 answers

, thread (id) comment (thread_id) , .

, -

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

:

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

, id .
thread2 . thread2, else , .

, :)

+1

:

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]')

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

, , , .

0

Source: https://habr.com/ru/post/1649678/


All Articles