2016-07-31 59 views
4

我想只在其父表中存在父项时插入行。Mysql - 检查行是否存在

线程1台

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

线程2台

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

评语表

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

现在,如果我这样做

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

应该失败,因为3存在于thread2表。

这可以通过检查线程表来实现。但没有它可能吗?没有做额外的查询?

更新

上面的表已经更新。在thread_type指表thread1 & thread2

+0

是否有可能在插入时会知道thread_type? –

+1

您应该考虑为线程创建一个表,并在该表中为'thread_type'创建一个字段,而不是。 – deed02392

回答

3

创建两个表之间的外键,使用线程(ID)为母公司和评论(thread_id单)作为孩子,应该做的伎俩。

这是你应该运行的命令 -

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

如果我有多个家长,该怎么办?它会起作用吗? – user6654248

+0

你可以举一个多个父母的例子吗?我不太了解这种情况。 –

+0

请参阅我的问题的更新。我更新了表 – user6654248

1

试试这个:

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

我假设,在ID的评语表的主键和自动递增。
以上查询将根据您的线程类型从thread2表中选择id。如果在thread2表中找到id,它将插入一个新行,否则插入零行,因为从父表中选择零行。

希望它能帮助:)

0

这可以这样做:

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 

所以如果有这样它会插入一行父母,否则不会插入任何东西。